可以使用Python的MySQL Connector来连接MySQL数据库,然后执行SQL查询语句。查询结果是一个结果集,每一行代表一个记录,可以使用for循环或者fetchone()函数来逐行遍历结果集,并对每一行进行处理。
以下是一个代码示例:
import mysql.connector
# 连接数据库
cnx = mysql.connector.connect(user='your_username', password='your_password',
host='your_host', database='your_database')
# 创建游标
cursor = cnx.cursor()
# 执行查询语句
query = "SELECT * FROM your_table"
cursor.execute(query)
# 遍历结果集
for (column1, column2, column3) in cursor:
# 处理每一行
# ...
# 关闭游标和数据库连接
cursor.close()
cnx.close()
如果你想截取查询结果的一部分,可以在执行查询语句时使用LIMIT关键字来限制结果集的大小:
query = "SELECT * FROM your_table LIMIT 10"
这样只会查询前10条记录。
温馨提示:答案为网友推荐,仅供参考