导包

python2使用mysqldb

python3使用pymysql

数据库连接池

  • DBUtils(推荐)
    可以连接多种数据库模块
  • pymysqldbpool
    只能使用pymysql模块

PS: 这两个包我在conda没找到,pip可以安装

连接池

DBUtils有两种连接池

  • PooledDB(多连接共用一个线程)
  • PersistentDB(每个连接单独一个线程)

PooledDB为例

导入

1
from DBUtils.PooledDB import PooledDB

连接数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
# 常用参数
PooledDB(
host='ip'
port='3306' # 端口, 默认3306
user='用户名'
password='密码'
db='默认数据库'
charset='字符集'
creator=pymysql # 数据库模块
mincached=0 # 初始化时的连接数, 默认0
maxcached=0 # 保留的最多连接数, 默认0
maxconnections=0 # 最多连接数, 默认0
)

这里无法确定返回类型(cursorclass),只能在获取cursor时设置

获取连接

1
2
pool = PooledDB()
conn = pool.connection()

获取游标

返回类型可以在这里设置,如元组型、字典型,默认元组

1
cursor = conn.cursor(cursorclass=pymysql.cursors.DictCursor)  #字典型

查询

1
cursor.execute(sql[, params])

返回受影响的行数

SQL拼接

1
cursor.execute('select * from t where a=\''+n+'\''')

有SQL注入风险,且拼接麻烦,可以使用format

SQL中存在’%‘时,不需要使用’%%‘转义,这种方式不会对SQL进行预编译,所以无需转义

占位符填充

当表名和字段名等非字段值时,应预先进行SQL拼接,占位符一般只对字段值使用

  • 用’%s‘作为占位符,params为元组或列表

    1
    2
    # 所有类型都是用%s
    cursor.execute('select * from t where a=%s', (name,))
  • 用别名’%(alaisname)s‘作为占位符,params为字典

    1
    cursor.execute('select * from t where a=%(name)s',{name=name})

    SQL中存在’%‘时,需要使用’%%‘转义,这种方式会对SQL预编译,%x均会认为是占位符

读取

获取记录数

1
cursor.rowcount

获取一条记录

获取下一条记录,并将rownumber+1

1
cursor.fetchone()

获取所有记录

获取所有记录,返回记录列表

1
cursor.fetchall()

记录的类型

在创建cursor时指定了返回类型,默认为tuple,当参数cursorclass=pymysql.cursors.DictCursor时返回字典,也可自定义类型

增删改

同查

execute后需要commitrollback

若在创建connection时,可设置autocommit=1,则会自动commit

1
2
3
4
try:
cursor.commit()
except:
cursor.rollback()

关闭资源

当使用with创建cursor时,将自动关闭cursor

1
2
3
# 手动关闭
cursor.close()
conn.close()

事务

当创建cursor时,自动开启事务

commit时,自动关闭事务

查询可以没有事务