首先下载安装连接器:
下载pythonconnector:https://dev.mysql.com/downloads/file/?id=484755,我的版本是Python3.7,64位,找到对应的msi下载。
也可以使用pip位Python安装具体参见:https://dev.mysql.com/doc/connector-python/en/connector-python-installation-binary.html
验证安装是否成功:
一般在你的Python下lib的site-package中(多版本的python安装时,默认是添加在path中的Python)
然后简单的使用,首先创建如下表:
然后写代码连接数据库并查询
import mysql.connector as ct
from mysql.connector import errorcode
def MyConnect(user,pwd,host,database):
con=None
try:
con=ct.connect(user=user,password=pwd,host=host,database=database)
except Exception:
print(“连接数据库出错!”)
exit(1)
else:
return con
def selectAll(con,TBname):
cursor=con.cursor()
query=“select * from {}”.format(TBname)
try:
cursor.execute(query)
except Exception:
print(“查询出错!”)
exit(1)
else:
return cursor
def main():
con=MyConnect(“root”,“123456”,“127.0.0.1”,“menagrie”)
curcor=selectAll(con,“pet”)
print(“名字\t主人\t品种\t性别\t生日\t死亡\n”)
for(name,owner,species,sex,birth,death)in curcor:
print(name,"\t",owner,"\t",species,"\t",sex,"\t",birth,"\t",death,"\t\n")
if name==“main”:
main()