一、普通 MySQL 连接方法
使用模块 MySQLdb 普通方式连接。
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import MySQLdb
conn = MySQLdb.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='test')
cursor = conn.cursor()
sql_1 = "select * from user where id = %s;" % (5,)
sql_2 = "select * from user \
where id = %s;" % (5,)
sql_3 = """
insert into user(username, password)
values("yuchaoshui", "123");
"""
try:
print cursor.execute(sql_1)
print cursor.fetchall()
print cursor.execute(sql_2)
print cursor.fetchall()
print cursor.execute(sql_3)
conn.commit()
except Exception as e:
print(e)
conn.rollback()
cursor.close()
conn.close()
execute() 返回结果表示影响的行数。cursor.fetchone() 取回一条结果。sql_1 直接一行写完,sql_2 换行写完, sql_3 多行写。 查询时不需要 commit() 操作,插入、更新、删除时需要 commit() 提交。
二、使用连接池连接MySQL
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import MySQLdb
from DBUtils.PooledDB import PooledDB
pool = PooledDB(MySQLdb, 5, host='127.0.0.1', port=3306, user='root', passwd='123', db=

本文介绍了两种Python连接MySQL的方法:1) 普通MySQL连接,使用MySQLdb模块;2) 使用连接池PooledDB进行连接,详细阐述了连接池的配置和使用。示例代码展示了如何执行SQL查询、插入操作,并处理异常。
最低0.47元/天 解锁文章

234

被折叠的 条评论
为什么被折叠?



