mysql python pymysql模块 增删改查 查询 字典游标显示

我们看到取得结果是一个元祖,但是不知道是哪个字段的,如果字段多的时候,就比较麻烦

'''
(1, 'mike', '123')
(2, 'jack', '456')
'''


用字典显示查询的结果,也可以查询到字段名

在拿游标时候加上
字典显示的游标
cur = conn.cursor(pymysql.cursors.DictCursor)
import pymysql



mysql_host = '192.168.0.106'
port = 3306
mysql_user = 'root'
mysql_pwd = '123'
encoding = 'utf8'

# 建立 连接mysql服务端

conn = pymysql.connect(
    host=mysql_host,  # mysql服务端ip
    port=port,  # mysql端口
    user=mysql_user,  # mysql 账号
    password=mysql_pwd,  # mysql服务端密码
    db='db10',  # 操作的库
    charset=encoding  # 读取字符串编码

)

# 拿到游标对象
cur = conn.cursor(pymysql.cursors.DictCursor)

'''
游标是给mysql提交命令的接口
mysql> 
把sql语句传递到这里
'''


# 执行sql语句
# 增、删、改
sql= 'select * from userinfo; '


# 把sql语句传给游标执行
# 让游标execute去帮我拼接字符串

rows = cur.execute(sql)

# 想看查询的内容 调游标对象
# fetchone 取第一条记录
print(cur.fetchone())
print(cur.fetchone())
print(cur.fetchone())
print(cur.fetchone())
print(cur.fetchone())
print(cur.fetchone())


# 执行完sql语句要关闭游标和mysql连接
cur.close()
conn.close()

'''
把字段也显示出来
{'id': 1, 'name': 'mike', 'pwd': '123'}
{'id': 2, 'name': 'jack', 'pwd': '456'}
{'id': 3, 'name': 'alex', 'pwd': '555'}
{'id': 4, 'name': 'peter', 'pwd': '989'}
{'id': 5, 'name': 'app', 'pwd': '123'}
{'id': 6, 'name': 'tom', 'pwd': '556'}
'''
原文地址:https://www.cnblogs.com/mingerlcm/p/9932542.html