时间:2021-07-01 10:21:17 帮助过:28人阅读
运行结果:
例2:
1 # -*- coding: utf-8 -*- 2 import MySQLdb 3 4 host = "localhost" 5 port = 3306 6 user = "root" 7 passwd = "pass" 8 db = "my_test_db" 9 10 conn = MySQLdb.connect(host=host, port=port, user=user, passwd=passwd, db = db, charset=‘utf8‘) # 打开数据库连接,并设置编码 11 print conn.get_autocommit() 12 conn.autocommit(1) # 设置自动提交,默认为false 13 print conn.get_autocommit() 14 cur = conn.cursor() # 使用cursor()方法获取操作游标 15 try: 16 sql = "insert into test values(‘str‘,1,-1)" 17 cur.execute(sql) 18 sql = "insert into te1st values(‘str‘,2,-2)" # 这一条出错了并不会影响上一条sql语句的执行 19 cur.execute(sql) 20 except: 21 conn.rollback() # 发生错误时回滚 22 sql = "select * from test" 23 cur.execute(sql) 24 print cur.fetchall() 25 sql = "insert into test values(‘str‘,3,-3)" # 一条正确的插入语句 26 cur.execute(sql) 27 sql = "select * from test" 28 cur.execute(sql) 29 print cur.fetchall() 30 conn.close() # 关闭数据库连接,一定要关闭,连接开太多会出问题
运行结果:
python-mysql
标签:nec sql ack 数据库事务 ola 方法 local 返回结果 png