数据库名:testdb
表名:testtable;中间有一列数据,字段名title
任务:连接数据库,输出 testtable 中所有的标题
方法1:使用 pymysql 管理 Python 和 MySQL 的连接
config={
"host":"127.0.0.1",
"port":3306,
"user":"root",
"password":"footba",
"database":"testdb",
}
def listtable_pymysql():
conn=pymysql.connect(**config) # 2个星号指作为多个参数传送;1个星号是作为1个字典参数传送;
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # DictCursor 以dict的形式返回操作结果。这样可以直接用字段名引用,例如 i[title]; 否则,返回tuple。
cursor.execute("SELECT * FROM testtable LIMIT 5") #输出前5条记录
result = cursor.fetchall() #获取记录
for i in result: #取记录并打印
print(i['title'])
cursor.close()
conn.close()
listtitle_pymysql()
方法2:使用 DBUtils 管理数据库连接
参考这篇:link
从某种层面看,数据库可看做服务端,而我们程序员(调用者)可看做客户端,而数据库连接就相当于HTTP连接,且实际上数据库连接的确包含 HTTP连接 和 Socket连接 两种方式。
另外,pymysql并不是线程安全的,所以当有多个线程同时使用pymysql操作数据库时,就会出现问题。
所以从线程安全和支持更高的并发的角度,我们一般会使用数据库连接池来解决,通常是使用第三方库,如 DBUtils。
from dbutils.pooled_db import PooledDB
POOL = PooledDB(
creator=pymysql, # 数据库驱动模块
host='127.0.0.1',
port=3306,
user='root',
password='footba',
database='testdb',
)
# 更多参数参考 https://webwareforpython.github.io/DBUtils/main.html#pooleddb-pooled-db-1
def listtable_dbutils():
conn=POOL.connection()
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("SELECT * FROM testtable LIMIT 5")
result = cursor.fetchall()
for i in result:
print(i['title'])
cursor.close()
conn.close()
listtable_dbutils()