1. 未使用连接池连接mysql
import MySQLdb
conn = MySQLdb.connect(host = '127.0.0.1', user ='user1', passwd = 'your-password', db ='db1', port = 3306)
cur = conn.cursor()
SQL ="select * from t1"
r = cur.execute(SQL)
r = cur.fetchall()
cur.close()
conn.close()
2. 使用连接池连接mysql
# -*- coding: utf-8 -*-
import MySQLdb
from DBUtils.PooledDB import PooledDB
#5为连接池里的最少连接数
pool = PooledDB(MySQLdb, 5, host = '127.0.0.1', user = 'user1', passwd = 'your-password', db = 'db1', port = 3306)
#后续每次需要数据库连接用connection()函数获取连接即可。
conn = pool.connection()
cur = conn.cursor()
SQL = "select * from t1"
r = cur.execute(SQL)
r = cur.fetchall()
cur.close()
conn.close()