Python連接Mysql常用的庫有MySQLdb,mysqlclient,MySQL Connector/Python,但是django文檔上推薦使用mysqlclient,以下截取django官網關於MySQL API的介紹。
MySQL DB API Drivers
The Python Database API is described in PEP 249. MySQL has three prominent drivers that implement this API:
•MySQLdb is a native driver that has been developed and supported for over a decade by Andy Dustman.
•mysqlclient is a fork of MySQLdb which notably supports Python 3 and can be used as a drop-in replacement for MySQLdb. At the time of this writing, this is the recommended choice for using MySQL with Django.
•MySQL Connector/Python is a pure Python driver from Oracle that does not require the MySQL client library or any Python modules outside the standard library.
All these drivers are thread-safe and provide connection pooling. MySQLdb is the only one not supporting Python 3 currently.
In addition to a DB API driver, Django needs an adapter to access the database drivers from its ORM. Django provides an adapter for MySQLdb/mysqlclient while MySQL Connector/Python includes its own.
mysqlclient連接MySQL讀取數據示例:
import MySQLdb
db = MySQLdb.connect(host="localhost", user="root", passwd="", db="demo")
c = db.cursor()
max_price = 5
c.execute("""SELECT * FROM think_node""")
r = c.fetchone()
print(r)
首先通過pip工具安裝mysqlclient庫,命令:pip install mysqlclient