mysql
python3中用pymysql
操作mysql数据库
pip3 install PyMySQL
import pymysqlconn = 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 pymysqlconn = 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语句字符串需要 ' 包裹。所以," 比较简单的避免歧义。