📜  使用 MySQL-Connector Python连接 MySQL 数据库

📅  最后修改于: 2022-05-13 01:55:06.424000             🧑  作者: Mango

使用 MySQL-Connector Python连接 MySQL 数据库

在使用Python时,我们需要使用数据库,它们可能是不同类型的,如 MySQL、SQLite、NoSQL 等。在本文中,我们将期待如何使用 MySQL Connector/ Python连接 MySQL 数据库。
Python的 MySQL 连接器模块用于将 MySQL 数据库与Python程序连接起来,它使用Python数据库 API 规范 v2.0 (PEP 249)。它使用Python标准库并且没有依赖项。

连接到数据库

在以下示例中,我们将使用 connect() 连接到 MySQL 数据库
例子:

Python3
# Python program to connect
# to mysql database
 
 
import mysql.connector
 
 
# Connecting from the server
conn = mysql.connector.connect(user = 'username',
                               host = 'localhost',
                              database = 'database_name')
 
print(conn)
 
# Disconnecting from the server
conn.close()


Python3
# Python program to connect
# to mysql database
 
 
from mysql.connector import connection
 
# Connecting to the server
conn = connection.MySQLConnection(user = 'username',
                              host = 'localhost',
                              database = 'database_name')
 
print(conn)
 
# Disconnecting from the server
conn.close()


Python3
# Python program to connect
# to mysql database
 
 
from mysql.connector import connection
 
 
dict = {
  'user': 'root',
  'host': 'localhost',
  'database': 'College'
}
 
# Connecting to the server
conn = connection.MySQLConnection(**dict)
 
print(conn)
 
# Disconnecting from the server
conn.close()


输出:

python-mysql-connect-1

同样,我们可以使用 connection.MySQLConnection() 类而不是 connect():
例子:

Python3

# Python program to connect
# to mysql database
 
 
from mysql.connector import connection
 
# Connecting to the server
conn = connection.MySQLConnection(user = 'username',
                              host = 'localhost',
                              database = 'database_name')
 
print(conn)
 
# Disconnecting from the server
conn.close()

输出:

python-mysql-connect-2

另一种方法是使用 '**'运算符在 connect()函数中传递字典:
例子:

Python3

# Python program to connect
# to mysql database
 
 
from mysql.connector import connection
 
 
dict = {
  'user': 'root',
  'host': 'localhost',
  'database': 'College'
}
 
# Connecting to the server
conn = connection.MySQLConnection(**dict)
 
print(conn)
 
# Disconnecting from the server
conn.close()

输出:

python-mysql-connect-3