如何使用Python函数查询MySQL数据库?
发布时间:2023-07-06 17:24:11
使用Python查询MySQL数据库可以使用MySQLdb模块或者pymysql模块来连接数据库和执行查询操作。以下是使用这两个模块的示例代码。
MySQLdb模块示例代码:
import MySQLdb
# 连接数据库
db = MySQLdb.connect(host="localhost", user="username", passwd="password", db="database_name")
# 创建游标对象
cursor = db.cursor()
# 执行查询语句
cursor.execute("SELECT * FROM table_name")
# 获取所有查询结果
results = cursor.fetchall()
# 遍历结果
for row in results:
column1 = row[0]
column2 = row[1]
# 其他列...
# 在控制台打印结果
print(column1, column2)
# 关闭游标和数据库连接
cursor.close()
db.close()
pymysql模块示例代码:
import pymysql
# 连接数据库
db = pymysql.connect(host="localhost", user="username", passwd="password", db="database_name")
# 创建游标对象
cursor = db.cursor()
# 执行查询语句
cursor.execute("SELECT * FROM table_name")
# 获取所有查询结果
results = cursor.fetchall()
# 遍历结果
for row in results:
column1 = row[0]
column2 = row[1]
# 其他列...
# 在控制台打印结果
print(column1, column2)
# 关闭游标和数据库连接
cursor.close()
db.close()
请确保将示例代码中的"host"、"user"、"passwd"、"db"和"table_name"替换为您实际的数据库连接信息和查询语句。另外,如果您选择使用pymysql模块,确保在代码之前先使用pip install pymysql命令安装该模块。
这些示例代码将执行一个简单的SELECT查询语句并将结果打印到控制台。您可以使用不同的查询语句,根据自己的需求选择查询结果或执行其他操作。
