1. 程式人生 > >python訪問數據庫

python訪問數據庫

from commit table 數據庫異常 影響 可視化 查詢 als ted

1. python DB api簡介

python DB api python訪問數據庫的統一接口規範,詳細可參考https://www.python.org/dev/peps/pep-0249/ python DB api中主要包括三個重要的對象 數據庫連接對象 connection,數據庫交互對象 cursor和數據庫異常類 exceptions

2. 使用python DB API訪問數據庫的流程

技術分享

3. python+MYSQL開發環境的配置

技術分享 python-mysql connector 用於python和mysql服務器進行連接,下載地址 https://sourceforge.net/projects/mysql-python/ syslog是一個Mysql可視化的管理工具, 下載地址 https://sqlyog.en.softonic.com/

4 connection對象

使用方法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()

5. 數據庫遊標對象cursor

cursor對象的方法   execute(op[,args]) 執行一個數據庫查詢和命令   fetchone() 取得結果集中下一行   fetchmany(size) 獲取結果集中下幾行   fetchall() 獲取結果集剩下的所有行   rowcount 最近一次execute返回的數據的行數或影響的行數   close() 關閉遊標對象 技術分享
我們在數據庫中建立了一個test數據庫,在其中建立了一個user表如下圖所示 技術分享 利用cursor對象來執行簡單的查詢語句
 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()

輸出

9 (1L, u‘name1‘) ((2L, u‘name2‘), (3L, u‘name3‘), (4L, u‘name4‘)) ((5L, u‘name5‘), (6L, u‘name6‘), (7L, u‘name7‘), (8L, u‘name8‘), (9L, u‘name9‘)) 技術分享 6. 事務處理 事務:訪問和更新數據庫的一個程序執行單元
原子性:事務中包括的諸操作要麽都做,要麽都不做 一致性:事務必須使數據庫從一致性狀態變到另一個一致性狀態 隔離性:一個事務的執行不能被其他事務幹擾 持久性:事務一旦提交,它對數據庫的改變是永久性的 開發中怎樣使用事務? 關閉自動commit:設置conn.autocommit(False) 正常結束事務:conn.commit() 異常結束事務:conn.rollback()
代碼示例
 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()

7. 銀行轉賬實例

假設張三要向王五轉賬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()








null



python訪問數據庫