python入门编程之mysql编程

python关于mysql方面的连接编程

前提:引入mysql模块MySQLdb,即:MySQL_python-1.2.5-cp27-none-win_amd64.whl

如果要用线程池,则要引用模块 PooledDB

import os
import MySQLdb

# import sys
# reload(sys)
# sys.setdefaultencoding('utf-8')
# 本实例讲的是单连接方式,如果要提高连接的利用率,可以考虑利用线程池:PooledDB,通过 from DBUtils.PooledDB import PooledDB
# pool = PooledDB(MySQLdb,5,host='localhost',user='root',passwd='pwd',db='myDB',port=3306) #5为连接池里的最少连接数
# conn = pool.connection()  #以后每次需要数据库连接就是用connection()函数获取连接就好了
# 后续步骤都一样,只是此时不是关闭连接,而是释放连接
# DBUtils下载地址:https://pypi.python.org/pypi/DBUtils/
conn=MySQLdb.connect(host="0.0.0.0",port=3306,user="username",
                     passwd="password",db="db",charset="utf8")
cursor=conn.cursor()
sql = "SELECT id,username,topic,rw FROM acls "
n = cursor.execute(sql)
print n
for row in cursor.fetchall():
        print  row
print "

 finish"
cursor.close()
conn.close()
原文地址:https://www.cnblogs.com/outpointexception/p/10558557.html