Python:PyMySQL模块读写MySQL数据

安装

https://pypi.org/project/PyMySQL/

pip install PyMySQL

1

PyMySQL 操作和MySQLdb 类似,可参考

Python编程:MySQLdb模块数据库的基本增删改查操作

代码示例

import pymysql
# 连接
conn = pymysql.Connect(host="127.0.0.1", port=3306, user="root",
                       passwd="123456",db="test")
# 创建游标
cursor = conn.cursor()
# 执行sql,并返回受影响行数
# rows = cursor.execute("insert into student(name, age, register_date, gender) "
#                              "values ('xiaoming', 23, '2018-12-30', 'M')")
# print(rows)
data = [
    ("student1", 23, "2018-01-31", "M"),
    ("student2", 24, "2018-02-27", "M"),
    ("student3", 28, "2018-03-31", "F"),
    ("student4", 26, "2018-04-30", "M"),
]
# 多条插入一起执行
# rows = cursor.executemany("insert into student(name, age, register_date, gender) "
#                               "values (%s, %s, %s, %s)",data)
# print(rows)
# 读取数据
cursor.execute("select * from student")
print(cursor.fetchall())
# 提交事务
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()