1. 程式人生 > >Python進行MySQL資料庫操作

Python進行MySQL資料庫操作

最近開始玩Python,慢慢開始喜歡上它了,以前都是用shell來實現一些自動化或者監控的操作,現在用Python來實現,感覺更棒,Python是一門很強大的面嚮物件語言,所以作為一個運維DBA或者運維來說,都應該學會用Python來提高工作效率。下面簡單的介紹一下Python DB API MySQLdb

使用Python DB API訪問資料庫的流程圖:

技術分享

在Centos下安裝MySQLdb模板(為了方便演顯,我用yum安裝,也是最快最省事的安裝):

yum install MySQL-python -y

如果安裝有ipython,可以看到它有非常多的物件,每個物件這裡就介紹ipython的安裝:

In [1]: import MySQLdb
In [2]: MySQLdb. MySQLdb.BINARY MySQLdb.NotSupportedError MySQLdb.escape_sequence MySQLdb.Binary MySQLdb.OperationalError MySQLdb.escape_string MySQLdb.Connect MySQLdb.ProgrammingError MySQLdb.get_client_info MySQLdb.Connection MySQLdb.ROWID MySQLdb.paramstyle MySQLdb.DATE MySQLdb.STRING MySQLdb.release MySQLdb.DATETIME MySQLdb.TIME MySQLdb.result MySQLdb.DBAPISet MySQLdb.TIMESTAMP MySQLdb.server_end MySQLdb.DataError MySQLdb.Time MySQLdb.server_init MySQLdb.DatabaseError MySQLdb.TimeFromTicks MySQLdb.string_literal MySQLdb.Date MySQLdb.Timestamp MySQLdb.test_DBAPISet_set_equality MySQLdb.DateFromTicks MySQLdb.TimestampFromTicks MySQLdb.test_DBAPISet_set_equality_membership MySQLdb.Error MySQLdb.Warning MySQLdb.test_DBAPISet_set_inequality MySQLdb.FIELD_TYPE MySQLdb.apilevel MySQLdb.test_DBAPISet_set_inequality_membership MySQLdb.IntegrityError MySQLdb.connect MySQLdb.thread_safe MySQLdb.InterfaceError MySQLdb.connection MySQLdb.threadsafety MySQLdb.InternalError MySQLdb.constants MySQLdb.times MySQLdb.MySQLError MySQLdb.debug MySQLdb.version_info MySQLdb.NULL MySQLdb.escape MySQLdb.NUMBER MySQLdb.escape_dict

 我們這裡主要說建立資料庫的連線物件connection,建立方法MySQLdb.connect(引數)

主要引數如下:

  引數名    型別      說明
  host     字串    MySQL伺服器地址
  port     數字      MySQL伺服器埠號
  user     字串    使用者名稱
  passwd   字串    密碼
  db       字串    資料庫名稱
  charset  字串    連線編碼

 connection物件支援的方法:

方法名        說明
cursor()    使用該連線建立並返回遊標
commit()    提交當前事務
rollback()  回滾當前事務
close()     關閉連線

例項講解:編輯connection.py


#!/usr/bin/env python
#coding:utf-8 #name: connection.py import MySQLdb #建立連線 conn = MySQLdb.connect( host = 127.0.0.1, port = 3306, user = root, passwd = 123456, db = python, charset = utf8 ) #建立一個學遊標物件 cursor = conn.cursor() print conn
print cursor #關閉遊標 關閉連線 cursor.close() conn.close()

執行結果:

[[email protected]server script]#python connection.py 
<_mysql.connection open to 127.0.0.1 at 23c1fa0>
<MySQLdb.cursors.Cursor object at 0x7f545cbf97d0>
[[email protected]-server script]#vim connection.py

可以看到成功連線了MySQL.

下面介紹一下游標物件: 用於執行查詢和獲取結果 

cursor物件支援的方法:

引數名               說明
execute(op[,args])   執行一個數據查詢命令
fetchone()           取的結果集的下一行
fetchmany(size)      獲取結果集的下幾行
fetchall()           獲取結果集中剩下的所有行
rowcount             最近一次execute返回的行數或影響行數
close()              關閉遊標物件

execute方法:執行SQL、將結果從資料為獲取到客戶端:
技術分享

fetch*()方法:移動rownumber,返回資料。

例項演示:(select查詢資料

技術分享

建立一張測試:

CREATE TABLE `user` (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) COLLATE utf8_bin DEFAULT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
mysql> select * from user;
+--------+----------+
| userid | username |
+--------+----------+
|      1 | user1    |
|      2 | user2    |
|      3 | user3    |
|      4 | user4    |
|      5 | user5    |
|      6 | user6    |
|      7 | user7    |
|      8 | user8    |
|      9 | user9    |
+--------+----------+
9 rows in set (0.00 sec)

編輯cursor.py檔案:

#!/usr/bin/env python
#coding:utf-8 #name: cursor.py import MySQLdb conn = MySQLdb.connect( host = 127.0.0.1, port = 3306, user = root, passwd = 123456, db = python, charset = utf8 ) cursor = conn.cursor() sql = select * from user cursor.execute(sql) #列印所有行資料 print cursor.rowcount #列印第一行資料 rs = cursor.fetchone() print 返回一條資料,rs #列印從第二行起的三行資料 rs = cursor.fetchmany(3) print 返回從第二條起的三條資料,rs #列印剩下的所有行數 rs = cursor.fetchall() print 返回剩下的行資料,rs cursor.close() conn.close()

執行程式:

[[email protected]server script]#python connection.py 
9
返回一條資料 (1L, uuser1)
返回從第二條起的三條資料 ((2L, uuser2), (3L, uuser3), (4L, uuser4))
返回剩下的行資料 ((5L, uuser5), (6L, uuser6), (7L, uuser7), (8L, uuser8), (9L, uuser9))

我們看到,每次使用fetch方法,都是在上一次fetch方法執行的結果的尾部開始。

如果我們想把表裡的資料格式化打印出來,因為從上面的結果我們可以看到返回的是元組的元組,我們通過for方法把它取出:

#!/usr/bin/env python
#coding:utf-8 #name: cursor.py import MySQLdb conn = MySQLdb.connect( host = 127.0.0.1, port = 3306, user = root, passwd = 123456, db = python, charset = utf8 ) cursor = conn.cursor() sql = select * from user cursor.execute(sql)
#獲取所有行的資料 rs = cursor.fetchall() for row in rs: print userid=%s, username=%s % row cursor.close() conn.close()

執行程式:

[[email protected]server script]#python cursor.py 
userid=1, username=user1
userid=2, username=user2
userid=3, username=user3
userid=4, username=user4
userid=5, username=user5
userid=6, username=user6
userid=7, username=user7
userid=8, username=user8
userid=9, username=user9

對MySQL的insert/delete/update的操作演示:

技術分享

編輯一個增刪改的指令碼iud.py

#!/usr/bin/env python
#coding:utf-8 #name: iud.py import MySQLdb conn = MySQLdb.connect( host = 127.0.0.1, port = 3306, user = root, passwd = 123456, db = python, charset = utf8 ) cursor = conn.cursor() #插入sql sql_insert = insert into user (userid,username) values (10,‘user10‘) #更新sql sql_update = update user set username= ‘name91‘ where userid=9 #刪除sql sql_delete = delete from user where userid < 3 #把一個事務放到一個try塊裡,如果出現異常就回滾 try: cursor.execute(sql_insert) print cursor.rowcount cursor.execute(sql_update) print cursor.rowcount cursor.execute(sql_delete) print cursor.rowcount #提交事務 conn.commit() #格式化增刪改後的資料查出來 select_sql = select * from user cursor.execute(select_sql) rs = cursor.fetchall() for row in rs: print userid=%s, username=%s % row except Exception as e: conn.rollback() #若有異常就回滾

執行程式,結果如下:

[email protected]server script]#python iud.py 
1
1
2
userid=3, username=user3
userid=4, username=user4
userid=5, username=user5
userid=6, username=user6
userid=7, username=user7
userid=8, username=user8
userid=9, username=name91
userid=10, username=user10

通過上面的簡單例子說明了通過Python的MySQLdb模組去進行MySQL資料庫操作,網上有很多例子,我是Python菜鳥,通過參加慕課網的一些簡單直接的python課程學習,個人感覺還不錯