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

猜你喜欢

转载自blog.csdn.net/weixin_42158523/article/details/83899447