脚本宝典收集整理的这篇文章主要介绍了Python学习笔记:操作数据库,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
mysql
python3中用pymysql
操作mysql数据库
pip3 install PyMySQL
import pymysql
conn = pymysql.Connect(host='127.0.0.1',port=3306,user='root',passwd='zk1991zk',db='mytest',charset='utf8')
cursor = conn.cursor()
sql = "select * from user"
cursor.execute(sql)
rs = cursor.fetchall()
print('rs:', rs)
for each in rs:
print(each)
更新数据库insert/update/delete
不同于select操作,这三个操作修改了数据库内容,所以需要commit(),否则数据库没有做相应的更改,但是也不会报错。
import pymysql
conn = pymysql.Connect(host='127.0.0.1', port=3306, user='root', passwd='zk1991zk',db="mytest")
conn.autocommit(False)
cursor = conn.cursor()
sqlInsert = "insert into user(id, name) value('6','Alex')"
sqlUpdate = "update user set name = 'Jason',email='sha5xiang@gmail.com' where id = '2'"
sqlDelete = "delete from user where id='6' "
try:
cursor.execute(sqlInsert)
print(cursor.rowcount)
cursor.execute(sqlUpdate)
print(cursor.rowcount)
cursor.execute(sqlDelete)
print(cursor.rowcount)
conn.commit()
except Exception as e:
print("Reason:", e)
conn.rollback()
cursor.close()
cursor.close()
实例 银行转账
注意点
- NoneType' object has no attribute 'encoding' ,之前指明的charset必须是"UTF8",不是"utf-8"/"UTF-8"
- MySQL语句后面必须有';',否则不会报错,也难以发现
- 数据库insert/update/delete操作需要commit()
- 在构造命令的时候,注意用 " 包裹起来,因为SQL语句字符串需要 ' 包裹。所以," 比较简单的避免歧义。
参考
python3操作MySQL数据库
[Python3读取Excel数据存入MySQL]()
以上是脚本宝典为你收集整理的Python学习笔记:操作数据库全部内容,希望文章能够帮你解决Python学习笔记:操作数据库所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。