python3 PyMySQL模块的安装和使用
2017年10月24日
没有评论
我们知道Python3和Python2是不兼容的,版本由2升级到3之后对MySQL数据库的访问也需要使用新的模块。此前的文章中已介绍过MySQLdb在Python2中的用法,今天介绍PyMySQL在Python3中的用法。
- 安装
- 直接通过pip安装:
pip install PyMySQL
- 直接通过pip安装:
- 示例
- 连接数据库
import pymysql try: conn = pymysql.connect(ip, 3306, user, password, db, charset='utf8', cursorclass=pymysql.cursors.DictCursor) except Exception as e: print("Exception throwed when connect to db: " + str(e))
- 插入数据
try: with conn.cursor() as cursor: sql = "insert into t_student(id, name) values (%d, %s)" rows=cursor.execute(sql, (s.id, s.name)) conn.commit() if rows == 1: print("Inserted.") else: print("Failed") except Exception as e: print("Exception throwed when insert data: " + str(e))