当前位置:Gxlcms > 数据库问题 > python-mysql

python-mysql

时间:2021-07-01 10:21:17 帮助过:28人阅读

# -*- 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) # 打开数据库连接 11 cur = conn.cursor() # 使用cursor()方法获取操作游标 12 try: 13 sql = "insert into test values(‘str‘,1,-1)" 14 cur.execute(sql) 15 sql = "insert into te1st values(‘str‘,2,-2)" # 这是一条错误的sql,因为事务机制,所以上1条sql语句也不会执行 16 cur.execute(sql) 17 conn.commit() # 提交到数据库执行 18 except: 19 conn.rollback() # 发生错误时回滚 20 sql = "select * from test" 21 cur.execute(sql) 22 print cur.fetchall() 23 sql = "insert into test values(‘str‘,3,-3)" # 一条正确的插入语句 24 cur.execute(sql) 25 conn.commit() # 提交到数据库执行 26 sql = "select * from test" 27 cur.execute(sql) 28 print cur.fetchall() 29 conn.close() # 关闭数据库连接,一定要关闭,连接开太多会出问题

 

运行结果:

 技术分享图片

 

例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   

人气教程排行