mysql数据库-5-1-pymysql操作mysql
pymysql连接mysql
import pymysql
def favorite_colors():
config = {
'user': 'root',
'password': 'root',
'host': 'db',
'port': '3306',
'database': 'knights'
}
connection = pymysql.connect(**config)
cursor = connection.cursor()
cursor.execute('SELECT * FROM favorite_colors')
results = [{name: color} for (name, color) in cursor]
cursor.close()
connection.close()
return results
事务操作
try:
cursor.execute(sql_1)
cursor.execute(sql_2)
cursor.execute(sql_3)
except Exception as e:
connect.rollback() # 事务回滚
print('事务处理失败', e)
else:
connect.commit() # 事务提交
print('事务处理成功', cursor.rowcount)# 关闭连接
cursor.close()
connect.close()
技术改变命运