python学习笔记12:操作mysql模块
mysql操作应先引入第三方模块pymysql
pip install pymysql
1.查询
1 import pymysql 2 # 打开数据库连接(密码必须是str类型,端口号必须是int类型) 3 connect = pymysql.connect(host='xxx.xx.x.xx', 4 user='ABC', 5 password='123456', 6 db='ABC', 7 port=3306, 8 charset='utf8') 9 cur = connect.cursor() #获取操作游标 10 # cur = connect.cursor(pymysql.cursors.DictCursor) #获取操作游标时可以指定类型 11 sql = 'select * from students; 12 # sql = 'select * from students limit 3; 13 cur.execute(sql) #执行sql语句 14 15 print(cur.fetchall()) #获取所有数据,二维数组 16 print(cur.fetchone()) #获取一条数据 17 print(cur.fetchmany(5)) #获取指定的数据条数,二维数组 18 19 print(cur.description) #获取表里的字段 20 21 cur.close() #关闭游标 22 connect.close() #关闭数据库连接
2.增加
1 import pymysql 2 # 打开数据库连接(autocommit=True修改后自动提交,就不需要connect.commit) 3 connect = pymysql.connect(host='xxx.xx.x.xx', 4 user='xxx', 5 password='123456', 6 db='xxx', 7 port=3306, 8 charset='utf8', 9 autocommit=True) 10 cur = connect.cursor() #获取游标操作 11 sql = "insert into students values (303,'小小','女',19,'一年级','北京');" 12 cur.execute(sql) #执行sql语句 13 # connect.commit() #提交事务 14 # connect.rollback() #回滚事务 15 cur.close() #关闭游标 16 connect.close() #关闭数据库连接
参考:https://www.runoob.com/python/python-mysql.html