【python】MySQLdb模塊

轉自:http://drizzlewalk.blog.51cto.com/2203401/448874/html

官網說明:python

參考:http://mysql-python.sourceforge.net/MySQLdb.htmlmysql

參考:http://mysql-python.sourceforge.net/MySQLdb-1.2.2/linux

yum install MySQL-python 最好先把python-devel安裝
MySQL-python-1.2.3-0.3.c1.1.el6.x86_64.rpmweb

一、創建鏈接,MySQLdb的connect()方法sql

conn1 = MySQLdb.connect(
    host='host',
    user='user',
    passwd= 'password',
    db = 'dbname',
    port=3306,
    charset='utf8'
    )
#####################
host:須要鏈接MySQL的主機ip
user:鏈接MySQL使用的用戶名
password:鏈接使用的用戶名密碼
dbname:默認打開的數據庫
port:端口,不須要引號
charset:字符集,若是輸出有亂碼,檢查MySQL字符集和python接口的是否一致
unix_socket:socket連接

 

二、獲取數據庫操做遊標(指針)數據庫

cur1 = conn1.cursor()
###############
因該模塊底層實際上是調用C API,因此須要先獲得當前指向數據庫的指針

 

三、對數據庫的操做session

>>> cur1 = conn1.cursor()                 
>>> do1 = cur1.execute("select * from t1")
>>> do1
56L
>>> cur1.close()
也能夠
>>> cur1 = conn1.cursor()                 
>>> sql1 = "select * from t1"
>>> do1 = cur1.execute(sql1)              
>>> do1
56L
>>> cur1.close()
##################
在python的IDE界面會有返回值,返回值是返回結果的行數

 

四、取得結果負載均衡

>>> cur1.fetchone()                 
(10L, 'ba')
fetchone(self):返回單獨一行的結果

>>> cur1.fetchall()
((10L, 'ba'), (10L, 'ba'), (10L, 'ba'), (10L, 'ba'), (1L, 'XXX'))
>>> cur1.fetchall()[-1]                  
(1L, 'XXX')
fetchall(self):返回所有結果集(全部行),類型是tuple元組,能夠用索引取出單個結果

>>> cur1.fetchmany(3)
((10L, 'ba'), (10L, 'ba'), (10L, 'ba'))
fetchmany(self, size=None):接收size條返回結果行.若是size的值大於返回的結果行的數量,則會返回cursor.arraysize條數據. 

 

五、關閉遊標和鏈接
commit()
rollback()
cur.close()
con.close()socket

 

五、異常處理

異常類別:https://www.python.org/dev/peps/pep-0249/#exceptions

參考:http://blog.csdn.net/zyz511919766/article/details/20546237

 

def get_instance_connection(instance_ip, instance_port, instance_database=''):
    try:
        conect_object = db.connect(user = , passwd = '', host = instance_ip, port = int(instance_port), db= instance_database)
        cursor_object = conect_object.cursor()
        return {'status':0, 'conect_object':conect_object, 'cursor_object':cursor_object}
    except Exception,e:
        return {'status':99, 'info':str(e)}

 

六、調整警告級別

http://blog.csdn.net/hewy0526/article/details/7695989

http://docs.python.org/library/warnings.html

 

參考: 

http://www.cnblogs.com/hzhida/archive/2012/08/02/2619848.html
http://www.oschina.net/code/snippet_16840_1811
http://zhidao.baidu.com/link?url=mR-vmXHlmXSVwGd6bcs0qR_6hbDHw48mS15Lt80PAkSrNvgQx3P00tZ5FMCx8FHGuSSyq9o8YfP9yoKdwd2Ena
http://www.linuxidc.com/Linux/2012-06/63620.htm
http://zhidao.baidu.com/link?url=fnFe5WTrlFknM0i0wxYfPyN9zeKF6KClwdSTUMuX3a-x8d5l7miI0qgvcsDbmaHM43SkKXBePv_5v4vbnA1BQK

 

DBUtil.PooledDB數據庫鏈接池:

源碼地址:http://www.webwareforpython.org/downloads/DBUtils/

參考:

http://developer.51cto.com/art/201003/189679.htm

1.1.1英文官網說明

http://www.webwareforpython.org/DBUtils/Docs/UsersGuide.html

0.9.4中文說明

http://wenku.baidu.com/link?url=QBmDTytv8gnmdfxmXk1rGY1IYNt-NDxPULSZ0c61ZxOvjiqJDUFCKanN4kU6rkSmtX7LMb4ZZnZkEeozgXsW6rV20ouw6Xlst8pBFqiwtzC

安裝:

python setup.py install

 

爲了使用 PooledDB 模塊,你首先須要經過建立 PooledDB 來設置數據庫鏈接池,傳遞以下參數(官方的說明能夠查看help(PooledDB)):

  •   creator: 能夠生成 DB-API 2 鏈接的任何函數或 DB-API 2 兼容的數據庫鏈接模塊。
  •   mincached: 啓動時開啓的空鏈接數量(缺省值 0 意味着開始時不建立鏈接)
  •   maxcached: 鏈接池使用的最多鏈接數量(缺省值 0 表明不限制鏈接池大小)
  •   maxshared: 最大容許的共享鏈接數量(缺省值 0 表明全部鏈接都是專用的)若是達到了最大數量,被請求爲共享的鏈接將會被共享使用。
  •   maxconnections: 最大容許鏈接數量(缺省值 0 表明不限制)
  •   blocking: 設置在達到最大數量時的行爲(缺省值 0 或 False 表明返回一個錯誤;其餘表明阻塞直到鏈接數減小)
  •   maxusage: 單個鏈接的最大容許複用次數(缺省值 0 或 False 表明不限制的複用)。當達到最大數值時,鏈接會自動從新鏈接(關閉和從新打開)
  •   setsession: 一個可選的SQL命令列表用於準備每一個會話,如 ["set datestyle to german", ...]
  •   creator 函數或能夠生成鏈接的函數能夠接受這裏傳入的其餘參數,例如主機名、數據庫、用戶名、密碼等。你還能夠選擇傳入creator函數的其餘參數,容許失敗重連和負載均衡
    Once you have set up the connection pool you can request
    database connections from that pool:
    
        db = pool.connection()
    
    You can use these connections just as if they were ordinary
    DB-API 2 connections. Actually what you get is the hardened
    SteadyDB version of the underlying DB-API 2 connection.
    
    Please note that the connection may be shared with other threads
    by default if you set a non-zero maxshared parameter and the DB-API 2
    module allows this. If you want to have a dedicated connection, use:
    
        db = pool.connection(shareable=False)
    
    You can also use this to get a dedicated connection:
    
        db = pool.dedicated_connection()
    
    If you don't need it any more, you should immediately return it to the
    pool with db.close(). You can get another connection in the same way.
    
    Warning: In a threaded environment, never do the following:
    
        pool.connection().cursor().execute(...)
    
    This would release the connection too early for reuse which may be
    fatal if the connections are not thread-safe. Make sure that the
    connection object stays alive as long as you are using it, like that:
    
        db = pool.connection()
        cur = db.cursor()
        cur.execute(...)
        res = cur.fetchone()
        cur.close() # or del cur
        db.close() # or del db
相關文章
相關標籤/搜索