python连接mysql
import pymysql
db = pymysql.connect(host="127.0.0.1", user="root", password="password", db="test", port=3306)
# 连接数据库
cursor = cur = db.cursor() # 获取数据库的游标
cursor.execute('select * from person') # 获取操作数据库的游标
#查询操作
results = cursor.fetchall() # 获取查询结果 cursor.fetchone() 查询一条
for row in results: # cursor.fetchmany(3) 查询前3条
print(row) # cursor.fetchall() 查询所有
#插入操作
cursor.execute("insert into person values(1,'mateng')") # execute也可以执行创建和修改库与表语句
db.commit()
提交
#使用execute(sql, args) 方法
cursor.execute("insert into person values(%d,%s)", args=(1, 'mateng'))
db.commit()
提交
#更新操作
cursor.execute("update person set name='tom' where id = 1")
db.commit()
#删除操作
cur.execute("delete from person where id=1")
#自动提交事务
db.autocommit(True) #自动提交事务