您当前的位置: 首页 >  Python

Python:PyMySQL模块读写MySQL数据

彭世瑜 发布时间:2018-02-03 21:13:34 ,浏览量:3

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

pip install PyMySQL

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()
关注
打赏
1688896170
查看更多评论

彭世瑜

暂无认证

  • 3浏览

    0关注

    2727博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.4354s