标签:bsp fetch 处理 project ffffff dev user 数据库 org
使用方法MySQLdb.connection(host,port,user,passwd,db,charset)返回一个connection对象
connection对象支持的方法有
方法 | 说明 |
cursor() | 使用该连接创建并返回的游标 |
commit() | 提交当前事务 |
rollback() | 回滚当前事务 |
close() | 关闭连接 |
连接数据库
1 import MySQLdb 2 conn = MySQLdb.Connect(host = ‘127.0.0.1‘, 3 port = 3306, 4 user = ‘root‘, 5 passwd = ‘123456‘, 6 db = ‘test‘, 7 charset=‘utf8‘) 8 cur = conn.cursor() 9 cur.close() 10 conn.close()
1 import MySQLdb 2 conn = MySQLdb.Connect(host = ‘127.0.0.1‘, 3 port = 3306, 4 user = ‘root‘, 5 passwd = ‘123456‘, 6 db = ‘test‘, 7 charset=‘utf8‘) 8 cur = conn.cursor() 9 sql = ‘select * from user‘ 10 cur.execute(sql) 11 print cur.rowcount 12 print cur.fetchone() 13 print cur.fetchmany(3) 14 print cur.fetchall() 15 cur.close() 16 conn.close()
输出
1 import MySQLdb 2 conn = MySQLdb.Connect(host = ‘127.0.0.1‘, 3 port = 3306, 4 user = ‘root‘, 5 passwd = ‘123456‘, 6 db = ‘test‘, 7 charset=‘utf8‘) 8 cur = conn.cursor() 9 sql_insert = "insert into user(usrid, usrname) values(10, ‘name10‘)" 10 sql_delete = "delete from user where usrid<3" 11 sql_update = "update user set usrname = ‘name91‘ where usrid=9" 12 try: 13 cur.execute(sql_insert) 14 cur.execute(sql_update) 15 cur.execute(sql_delete) 16 conn.commit() 17 except Exception as e: 18 print e 19 conn.rollback() 20 cur.close() 21 conn.close()
假设张三要向王五转账100元,其转账流程如下图所示
1 import MySQLdb 2 def checkAccountAvailable(conn,username): 3 cur = conn.cursor() 4 sql = "select * from account where username=‘%s‘"%username 5 print sql 6 cur.execute(sql) 7 r = cur.rowcount 8 print r 9 cur.close() 10 return r 11 12 def account(conn, username): 13 cur=conn.cursor() 14 sql = "select * from account where username=‘%s‘"%username 15 print sql 16 cur.execute(sql) 17 account = cur.fetchone()[1] 18 cur.close 19 return account 20 def main(): 21 conn = MySQLdb.Connect(host = ‘127.0.0.1‘, 22 port = 3306, 23 user = ‘root‘, 24 passwd = ‘123456‘, 25 db = ‘test‘, 26 charset=‘utf8‘) 27 if checkAccountAvailable(conn,‘zhangsan‘) and checkAccountAvailable(conn,‘wangwu‘): 28 if account(conn,"zhangsan") >= 100: 29 try: 30 cur = conn.cursor() 31 cur.execute("update account set account=account-100 where username=‘zhangsan‘") 32 cur.execute("update account set account=account+100 where username=‘wangwu‘") 33 conn.commit() 34 except Exception as e: 35 print e 36 conn.rollback() 37 finally: 38 cur.close() 39 else: 40 print "zhangsan has not enough money" 41 else: 42 print "account not existed" 43 44 conn.close() 45 main()
标签:bsp fetch 处理 project ffffff dev user 数据库 org
原文地址:http://www.cnblogs.com/blackclody/p/6893235.html