Python 连接 MySQL

夙愿已清 提交于 2019-11-30 09:34:11

Python 连接 MySQL

安装MySQL驱动

pip insatll pymysql

操作数据库

import pymysql

# 1.打开数据库连接(地址,账号,密码,数据库)
conn = pymysql.connect('localhost', 'root', '123456', 'mydb')
# 2.创建一个游标对象
cursor = conn.cursor()
# 3.插入一行记录,注意MySQL的占位符是%s
cursor.execute('insert into user (age, name, create_time, birthday) values (%s, %s, %s, %s)', [21, 'xiao', '2019-11-25 15:33:59', '2019-11-25'])
# 提交事务
conn.commit()

# 执行查询
cursor.execute('select * from user')
# 查询得到结果集
values = cursor.fetchall()
# 遍历结果集
for v in values:
    print('查询结果:', v)
# 1.关闭游标
cursor.close()
# 2.关闭连接
conn.close()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!