当前位置:Gxlcms > 数据库问题 > mysql python pymysql模块 增删改查 查询 字典游标显示

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

时间:2021-07-01 10:21:17 帮助过:31人阅读

‘‘‘
(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‘}
‘‘‘

 

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

标签:charset   mys   info   imp   第一条   接口   操作   nec   字符   

人气教程排行