1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python pymysql模块 链接mysql 遍历查询结果的方法 详解

python pymysql模块 链接mysql 遍历查询结果的方法 详解

时间:2019-06-06 14:33:32

相关推荐

python pymysql模块 链接mysql 遍历查询结果的方法 详解

目录

python链接mysql的方法

遍历字段获取值

完整代码

python链接mysql的方法

import jsonimport pymysqldef connect_mysql():conn = pymysql.connect(host='localhost',user='root',password='root',db='test',port=3306,charset='utf8')return conn

遍历字段获取值

# 获取游标对象cursor = conn.cursor()# 查询 SQL 语句sql = "select id,name,score from students;"# 执行 SQL 语句 返回值就是 SQL 语句在执行过程中影响的行数row_count = cursor.execute(sql)print("SQL 语句执行影响的行数%d" % row_count)# 取出结果集中一行数据,例如:(1, '张三',89)# print(cursor.fetchone())# 取出结果集中的所有数据, 例如:((1, '张三',89), (2, '李四',88), (3, '王五',90))for line in cursor.fetchall():print(line)#获取单个字段的值print("id的值"+line[0])print("name的值"+line[1])print("score的值"+line[2])

完整代码

import pymysql# 创建连接对象conn = pymysql.connect(host='localhost', port=3306, user='root', password='root',database='test', charset='utf8')# 获取游标对象cursor = conn.cursor()# 查询 SQL 语句sql = "select id,name,score from students;"# 执行 SQL 语句 返回值就是 SQL 语句在执行过程中影响的行数row_count = cursor.execute(sql)print("SQL 语句执行影响的行数%d" % row_count)# 取出结果集中一行数据,例如:(1, '张三',89)# print(cursor.fetchone())# 取出结果集中的所有数据, 例如:((1, '张三',89), (2, '李四',88), (3, '王五',90))for line in cursor.fetchall():print(line)#获取单个字段的值print("id的值"+line[0])print("name的值"+line[1])print("score的值"+line[2])# 关闭游标cursor.close()# 关闭连接conn.close()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。