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()

執行結果:

[root@Test-server script]#python connection.py 
<_mysql.connection open to '127.0.0.1' at 23c1fa0>
<MySQLdb.cursors.Cursor object at 0x7f545cbf97d0>
[root@Backup-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()

運行程序:

[root@Test-server script]#python connection.py 
9
返回一條數據 (1L, u'user1')
返回從第二條起的三條數據 ((2L, u'user2'), (3L, u'user3'), (4L, u'user4'))
返回剩下的行數據 ((5L, u'user5'), (6L, u'user6'), (7L, u'user7'), (8L, u'user8'), (9L, u'user9'))

我們看到,每次使用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()

執行程序:

[root@Test-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()  #若有異常就回滾

執行程序,結果如下:

root@Test-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課程學習,個人感覺還不錯,至少我學會了使用Python去操作MySQL。

參考資料:

 https://www.python.org/dev/peps/pep-0249/

http://www.imooc.com

 

 

作者:陸炫志

出處:xuanzhi的博客 http://www.cnblogs.com/xuanzhi201111

您的支持是對博主最大的鼓勵,感謝您的認真閱讀。本文版權歸作者所有,歡迎轉載,但請保留該聲明。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM