Python 连接 MySQL 数据库教程:MySQLdb 和 pymysql 模块
可以使用 Python 中的 MySQLdb 或 pymysql 模块来连接 mysql 数据库。以下是连接 mysql 数据库的示例代码:
使用 MySQLdb 模块:
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect(host='localhost',user='root',passwd='password',db='test')
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 执行SQL语句
cursor.execute('SELECT VERSION()')
# 获取一条数据
data = cursor.fetchone()
# 输出结果
print('Database version : %s ' % data)
# 关闭数据库连接
db.close()
使用 pymysql 模块:
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost',user='root',passwd='password',db='test')
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 执行SQL语句
cursor.execute('SELECT VERSION()')
# 获取一条数据
data = cursor.fetchone()
# 输出结果
print('Database version : %s ' % data)
# 关闭数据库连接
db.close()
其中,host、user、passwd、db 分别表示数据库的地址、用户名、密码和数据库名称,可以根据实际情况进行修改。
原文地址: https://www.cveoy.top/t/topic/ofUB 著作权归作者所有。请勿转载和采集!