Python 連線 MySQL

餘子越發表於2019-02-16

一、普通 MySQL 連線方法

  使用模組 MySQLdb 普通方式連線。

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

import MySQLdb

conn = MySQLdb.connect(host=`127.0.0.1`, port=3306, user=`root`, passwd=`123`, db=`test`)
cursor = conn.cursor()

sql_1 = "select * from user where id = %s;" % (5,)
sql_2 = "select * from user 
         where id = %s;" % (5,)
sql_3 = """
           insert into user(username, password)
           values("yuchaoshui", "123");
        """

try:
    print cursor.execute(sql_1)
    print cursor.fetchall()

    print cursor.execute(sql_2)
    print cursor.fetchall()

    print cursor.execute(sql_3)
    conn.commit()

except Exception as e:
    print(e)
    conn.rollback()

cursor.close()
conn.close()

   execute() 返回結果表示影響的行數。cursor.fetchone() 取回一條結果。sql_1 直接一行寫完,sql_2 換行寫完, sql_3 多行寫。 查詢時不需要 commit() 操作,插入、更新、刪除時需要 commit() 提交。

二、使用連線池連線MySQL

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

import MySQLdb
from DBUtils.PooledDB import PooledDB

pool = PooledDB(MySQLdb, 5, host=`127.0.0.1`, port=3306, user=`root`, passwd=`123`, db=`test`)
conn = pool.connection()
cursor = conn.cursor()

sql_1 = "select * from user where id = %s;" % (5,)
sql_2 = "select * from user 
         where id = %s;" % (5,)
sql_3 = """
           insert into user(username, password)
           values("yuchaoshui", "123");
        """
try:
    print cursor.execute(sql_1)
    print cursor.fetchall()

    print cursor.execute(sql_2)
    print cursor.fetchall()

    print cursor.execute(sql_3)
    conn.commit()

except Exception as e:
    print(e)
    conn.rollback()

cursor.close()
conn.close()

   5 為連線池裡的最少連線數, 以後每次需要資料庫連線就是用connection()函式獲取連線就好了

  • PooledDB 的預設值
PooledDB(self, creator, mincached=0, maxcached=0, maxshared=0, maxconnections=0, blocking=False, maxusage=None, setsession=None, reset=True, failures=None, ping=1, *args, **kwargs)
  • PooledDB的引數:
  1. mincached,最少的空閒連線數,如果空閒連線數小於這個數,pool會建立一個新的連線
  2. maxcached,最大的空閒連線數,如果空閒連線數大於這個數,pool會關閉空閒連線
  3. maxconnections,最大的連線數,
  4. blocking,當連線數達到最大的連線數時,在請求連線的時候,如果這個值是True,請求連線的程式會一直等待,直到當前連線數小於最大連線數,如果這個值是False,會報錯,
  5. maxshared , 當連線數達到這個數,新請求的連線會分享已經分配出去的連線

三、模組匯入連線 MySQL

  以連線池的方式,編寫模組 mysqlhelper.py,可以在專案的其他地方匯入MySQL連線例項即可使用。 模組點此下載 mysqlhelper.py

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

from __future__ import print_function
from DBUtils.PooledDB import PooledDB
import MySQLdb
import sys

__all__ = [`m`] + ["m"+str(i) for i in range(2, 11)]

class MH(object):
    def __init__(self):
        try:
            print("Connecting MySQL Server {0}@{1}:{2} ..".format(
                self.__class__.db, self.__class__.host, self.__class__.port), end=`.`)

            self.conn = self.__class__.pool.connection()
            self.cursor = self.conn.cursor()
            print(` ok!`)
        except Exception, e:
            print("pool.connection error: {0}".format(e))

    def select(self, query=``):
        try:
            self.effect = self.cursor.execute(query)
            return self.cursor
        except Exception as e:
            print("select error: {0}".format(e))

    def update(self, query=``):
        try:
            self.effect = self.cursor.execute(query)
            self.conn.commit()
        except Exception as e:
            print("update error: {0}".format(e))
            self.conn.rollback()
            self.effect = 0


# M2 類繼承自 M1,表示一個新的 MySQL 連線池。
# 如果需要新的連線池 ,按照如下格式新增即可。
class MH2(MH):
    pass


def init_pool(M,
            host=`127.0.0.1`, 
            port=3306, 
            user=`root`, 
            password=``, 
            database=`test`,
            pool_size=5): 

    M.host = host
    M.port = int(port)
    M.user = user
    M.password = password
    M.db = database
    M.pool_size = pool_size
    try:
        M.pool = PooledDB(MySQLdb, 
            M.pool_size,
            host=M.host,
            port=M.port,
            user=M.user,
            passwd=M.password,
            db=M.db)
    except Exception, e:
        print("PooledDB init error: {0}".format(e))
        exit(1)


# 初始化連線池,可以有多個。第一個引數是前面手動定義的連線池類。
init_pool(MH, `127.0.0.1`, 3306, `root`, `123`, `test`)
init_pool(MH2, `12.55.5.61`, 3306, `root`, `123`, `test`)


# 定義將要被匯出的MySQL例項。 一個連線池可同時提供多個例項物件。
m = MH()
m2 = MH2()


if __name__ == "__main__":
    pass
    #print "
m info:"
    #print m.select("select * from user;").fetchone()
    #print m.effect
    #print m.select("select * from user;").fetchall()
    #print m.effect
    #m.update("insert into user(username,password) values(`haha`, `heihei`);")
    #print m.effect
    ##################################################
    #print "
m2 info:"
    #print m2.select("select * from user;").fetchone()
    #print m2.effect
    #print m2.select("select * from user;").fetchall()
    #print m2.effect
    #m2.update("insert into user(username,password) values(`haha`, `heihei`);")
    #print m2.effect

  • 使用方法
#!/usr/bin/env python
# _*_ coding:utf-8 _*_

from mysqlhelper import m, m2
import time

def test():
    print "
m info:"
    print m.select("select * from user;").fetchone()
    print m.effect
    print m.select("select * from user;").fetchall()
    print m.effect
    m.update("insert into user(username,password) values(`haha`, `heihei`);")
    print m.effect
    
    #################################################
    
    print "
m2 info:"
    print m2.select("select * from user;").fetchone()
    print m2.effect
    print m2.select("select * from user;").fetchall()
    print m2.effect
    m2.update("insert into user(username,password) values(`haha`, `heihei`);")
    print m2.effect

if __name__ == `__main__`:
    test()

相關文章