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

2021年3月24日13:48:28 发表评论 798 次浏览

使用Python时, 我们需要使用数据库, 它们的类型可能不同, 例如MySQL, SQLite, NoSQL等。在本文中, 我们将期待如何使用MySQL Connector / Python连接MySQL数据库

Python的MySQL连接器模块用于将MySQL数据库与Python程序连接, 它使用Python数据库API规范v2.0(PEP 249)进行连接。它使用Python标准库, 没有任何依赖关系。

连接到数据库

在下面的示例中, 我们将使用connect()

例子:

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

输出如下:

python-mysql-connect-1

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

例子:

# Python program to connect
# to mysql databse
  
  
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()函数中传递字典:

例子:

# Python program to connect
# to mysql databse
  
  
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

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: