首先是工具库的安装
pip install mysql-connector
连接数据库
#连接数据库 #常规连接方式 conn = mysql.connector.connect(user='root', password='1111', database='test') #我用了最新的8.0的mysql踩到这个坑,要在后面加上auth_plugin参数解决 conn = mysql.connector.connect(user="root", password="1111", database="test",auth_plugin='mysql_native_password') cursor = conn.cursor()
数据库操作
#创建user表 cursor.execute("create table user(id varchar(20) primary key,name varchar(20))") #插入数据 cursor.execute("insert into user(id,name) values(%s,%s)",["1","Rose"]) cursor.execute("insert into user(id,name) values(%s,%s)",["2","Curry"]) #查询数据 cursor.execute('select * from user where id = %s', ('1',)) values = cursor.fetchall() print (values) #提交数据 conn.commit() #查询数据库是否在运行 cursor = conn.cursor() #关闭cursor和conn cursor.close() conn.close()
#查询输出 "C:xxxxx路径" [('1', 'Rose')] [('2', 'Curry')]