原创

Python:PyMySQL模块读写MySQL数据

本文为博主原创文章,欢迎转载,请注明出处
本文链接:https://pengshiyu.blog.csdn.net/article/details/79249501

安装
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()
文章最后发布于: 2018-02-03 21:13:34
展开阅读全文
0 个人打赏

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览