1. 程式人生 > >基於Python庫pymysql操作資料庫的方法

基於Python庫pymysql操作資料庫的方法

適用環境

python版本 >=2.6或3.3

mysql版本>=4.1

安裝方法

1.  手動安裝,請先下載。下載地址:https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X

其中的X.X是版本(目前可以獲取的最新版本是0.6.6)。

下載後解壓壓縮包。在命令列中進入解壓後的目錄,執行如下的指令:

1

python setup.py install

 

 

2.  可以使用pip安裝也可以手動下載安裝。

使用pip安裝,在命令列執行如下命令:

2

pip install pymysql

 

 

使用方法

連線資料庫的方法:

1

2

3

4

5

6

7

8

9

10

import pymysql.cursors

# Connect to the database

connection = pymysql.connect(host='127.0.0.1',

                             port=3306,

                             user='root',

                             password='test123456',

                             db='employees',

                             charset='utf8mb4',

                             #設定遊標為字典形式

                             cursorclass=pymysql.cursors.DictCursor)

 

 

 

 

 

 

 

或者用字典的形式:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

import pymysql.cursors

 

config = {

          'host':'127.0.0.1',

          'port':3306,

          'user':'root',

          'password':'zhyea.com',

          'db':'employees',

          'charset':'utf8mb4',

          'cursorclass':pymysql.cursors.DictCursor,

          }

 

# Connect to the database

connection = pymysql.connect(**config)

 

 

 

 

 

 

 

 

 

建立資料庫表:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

#!/usr/bin/python3

 

import pymysql

 

# 開啟資料庫連線

db = pymysql.connect("localhost","testuser","test123","TESTDB" )

 

# 使用 cursor() 方法建立一個遊標物件 cursor

cursor = db.cursor()

 

# 使用 execute() 方法執行 SQL,如果表存在則刪除 cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

 

# 使用預處理語句建立表

sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )"""

 

cursor.execute(sql)

 

# 關閉資料庫連線

db.close()

 

 

 

 

 

 

 

 

 

 

 

 

 

插入\更新\刪除資料:

由於資料庫的操作是指令型別的操作,所以在獲取cursor後,需要執行sql語句。因為配置預設自動提交,故在執行sql語句後需要主動commit(結束所有操作後不要忘記關閉連線!):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

# 執行sql語句

 

import pymysql

 

# 開啟資料庫連線

db = pymysql.connect("localhost","testuser","test123","TESTDB" )

 

# 使用cursor()方法獲取操作遊標

cursor = db.cursor()

 

# 執行sql語句,插入記錄

sql = "INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)"

#也可以如下插入記錄

sql = "INSERT INTO EMPLOYEE(FIRST_NAME,  LAST_NAME, AGE, SEX, INCOME) VALUES ('%s', '%s', '%d', '%c', '%d' )" %  ('Mac', 'Mohan', 20, 'M', 2000)

#也可以如下插入記錄

sql = ''INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('%s', '%s', '%d', '%c', '%d')"

cursor.execute(sql, ('Mac', 'Mohan', 20, 'M', 2000)

#注意:如果用 input 輸入做成多方法sql的輸入,VALUES括號內的值char格式的需要帶引號。

# 執行sql語句,更新記錄

sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')

# SQL 刪除語句

sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)

try:

    # 執行sql語句

    cursor.execute(sql)

    # 提交到資料庫執行

    db.commit()

except:

    # 如果發生錯誤則回滾

    db.rollback()

# 關閉資料庫連線

db.close()

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

查詢資料:

結束所有操作後不要忘記關閉連線!

1

2

3

4

5

6

7

8

9

10

11

12

13

# 執行sql語句,進行查詢

sql = ''SELECT * FROM EMPLOYEE''

        try:

            cursor.execute(sql)

            # 獲取查詢結果

            result = cursor.fetchone()

            #result = cursor.fetchmany()

            #result = cursor.fetchall()

            print(result)

         except:

            print ("Error: unable to fetch data")

#關閉資料庫連線

connection.close();

 

 

 

 

 

 

 

 

錯誤處理

DB API中定義了一些資料庫操作的錯誤及異常,下表列出了這些錯誤和異常:

異常 描述
Warning 當有嚴重警告時觸發,例如插入資料是被截斷等等。必須是 StandardError 的子類。
Error 警告以外所有其他錯誤類。必須是 StandardError 的子類。
InterfaceError 當有資料庫介面模組本身的錯誤(而不是資料庫的錯誤)發生時觸發。 必須是Error的子類。
DatabaseError 和資料庫有關的錯誤發生時觸發。 必須是Error的子類。
DataError 當有資料處理時的錯誤發生時觸發,例如:除零錯誤,資料超範圍等等。 必須是DatabaseError的子類。
OperationalError 指非使用者控制的,而是操作資料庫時發生的錯誤。例如:連線意外斷開、 資料庫名未找到、事務處理失敗、記憶體分配錯誤等等操作資料庫是發生的錯誤。 必須是DatabaseError的子類。
IntegrityError 完整性相關的錯誤,例如外來鍵檢查失敗等。必須是DatabaseError子類。
InternalError 資料庫的內部錯誤,例如遊標(cursor)失效了、事務同步失敗等等。 必須是DatabaseError子類。
ProgrammingError 程式錯誤,例如資料表(table)沒找到或已存在、SQL語句語法錯誤、 引數數量錯誤等等。必須是DatabaseError的子類。
NotSupportedError 不支援錯誤,指使用了資料庫不支援的函式或API等。例如在連線物件上 使用.rollback()函式,然而資料庫並不支援事務或者事務已關閉。 必須是DatabaseError的子類。

 

 

 

 

 

 

 

 

 

 

 

 

 

Python資料庫連線池

python程式設計中可以使用pymysql進行資料庫連線及增刪改查操作,但每次連線mysql請求時,都是獨立的去請求訪問,比較浪費資源,而且訪問數量達到一定數量時,對mysql的效能會產生較大的影響。因此實際使用中,通常會使用資料庫的連線池技術,來訪問資料庫達到資源複用。

æ°æ®åºè¿æ¥æ± 

python的資料庫連線池包:DBUtils

DBUtils提供兩種外部介面:

  • PersistentDB:提供執行緒專用的資料庫連線,並自動管理連線。
  • PooledDB:提供執行緒間可共享的資料庫連線,並自動管理連線。 

1.  DBUtils包安裝: pip install DBUtils

2.  手動下載 DBUtils 安裝包,解壓後,使用python setup.py install 命令進行安裝

完整程式碼如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

 

#-*- coding:utf-8 -*-
#libby_db_pool.py
#執行緒間可共享的資料庫連線

 

import pymysql
from DBUtils.PooledDB import PooledDB #資料庫連線池


class opMysql(object):

    __pool = None
    
    #建構函式,建立資料庫連線、遊標
    def __init__(self):
        self.coon = opMysql.getMysqlconn()
        self.cur = self.coon.cursor(cursor=pymysql.cursors.DictCursor)

    #資料庫連線池連線
    #@staticmethod
    def getMysqlconn():
        if opMysql.__pool is None:
            __pool = PooledDB(creator=pymysql, mincached=1, maxcached=20, host=mysqlInfo['host'], user=mysqlInfo['user'], passwd=mysqlInfo['passwd'], db=mysqlInfo['db'], port=mysqlInfo['port'], charset=mysqlInfo['charset'])
            print("Connection pooling...")
            print()
        return __pool.connection()

    #插入\更新\刪除sql
    def op_Insert(self, sql):
        print('op_insert:', sql)
        insert_num = self.cur.execute(sql)
        print('mysql sucess ', insert_num)
        self.coon.commit()
        return insert_num

    #查詢
    def op_Select(self, sql):
        print('op_select:', sql)
        self.cur.execute(sql)  # 執行sql
        #select_res = self.cur.fetchone()  # 返回結果為字典
        #select_res = self.cur.fetchmany()
        select_res = self.cur.fetchall()
        print('op_select:', select_res)
        return select_res

    #釋放資源
    def cl_dispose(self):
        self.coon.close()
        self.cur.close()
#etcpdw_dev   test-1  Id  userId   userName   itmeId   itemName   rating
#INSERT INTO test(Id, userId, userName, itemId, itemName, rating) VALUES (10, 4, '小白', 1, '布',4)
#INSERT INTO test_1 (F,L) VALUES (3,'ba')
mysqlInfo = {
    "host": '1.2.3.4',
    "user": 'root,
    "passwd": 'test123456',
    "db": 'localhost',
    "port": 3306,
    "charset": 'utf8'
}

if __name__ == '__main__':
    
    opm = opMysql()
    sql = input("要執行的SQL語句:")
    res = opm.op_Select(sql)
    #res = opm.op_Insert(sql)
    #釋放資源
    opm.cl_dispose()