当前位置:
首页 > Python基础教程 >
-
python-pymysql获取字段名称-获取内容方式
这篇文章主要介绍了python-pymysql获取字段名称-获取内容方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
python-pymysql获取字段名称-获取内容
获取字段名称-获取内容
import pymysql
# 连接数据库
db = pymysql.connect(host='192.168.254.109', user='root', password='123456', database='blog')
# 使用cursor()方法创建一个游标对象
cursor = db.cursor()
# 查询语句
sql = """select * from a"""
# 执行 sql语句
cursor.execute(sql)
# 查询全部
results = cursor.fetchall()
# 获取表结构 cursor.description
fields = [field[0] for field in cursor.description]
# 序列化 成字典 zip 把两个可迭代对象合并成2维元组。然后用dict 转化为字典。
res = [dict(zip(fields, result)) for result in results]
print(res)
# 关闭游标和数据库的连接
cursor.close()
db.close()
pro_res = """ [{'id': 1, 'name': '111', 'create_time': datetime.datetime(2022, 1, 6, 11, 6, 42), 'update_time': datetime.datetime(2022, 1, 6, 11, 6, 42)},
{'id': 2, 'name': '222', 'create_time': datetime.datetime(2022, 1, 6, 11, 36, 4), 'update_time': datetime.datetime(2022, 1, 6, 11, 36, 4)}]"""
若只执行 results = cursor.fetchall()
1 产出的结果都是 元组 且不包含字段名称的.
2 使用pandas去解析这个 results也无法产出字段的.
python代码获取mysql字段名和注释
# coding=utf-8
import pymysql
def get_mysql_zi_duan():
conn = pymysql.connect(host='192.168.', port=3306, user='hs', passwd='xi', db='db_x', charset='utf8')
cursor01 = conn.cursor()
cursor01.execute(
"select column_name, column_comment from information_schema.columns where table_schema ='db_xingyun' and table_name = 'api_ind_guan_yi_s_d'")
all_info = cursor01.fetchall() # 数据库字段名和注释
# print(all_info)
zi_duan_ming = []
zhushi = []
for data in all_info:
zi_duan_ming.append(data[0])
zhushi.append(data[1])
# print(data[0])
print(str(zi_duan_ming).replace('[','').replace(']','').replace("'",''))
print(zhushi)
cursor01.close()
conn.close()
if __name__ == '__main__':
# 获取一个表的 所有字段名
get_mysql_zi_duan()
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
原文链接:https://blog.csdn.net/Ly_Word/article/details/122340439
栏目列表
最新更新
求1000阶乘的结果末尾有多少个0
详解MyBatis延迟加载是如何实现的
IDEA 控制台中文乱码4种解决方案
SpringBoot中版本兼容性处理的实现示例
Spring的IOC解决程序耦合的实现
详解Spring多数据源如何切换
Java报错:UnsupportedOperationException in Col
使用Spring Batch实现批处理任务的详细教程
java中怎么将多个音频文件拼接合成一个
SpringBoot整合ES多个精确值查询 terms功能实
SQL Server 中的数据类型隐式转换问题
SQL Server中T-SQL 数据类型转换详解
sqlserver 数据类型转换小实验
SQL Server数据类型转换方法
SQL Server 2017无法连接到服务器的问题解决
SQLServer地址搜索性能优化
Sql Server查询性能优化之不可小觑的书签查
SQL Server数据库的高性能优化经验总结
SQL SERVER性能优化综述(很好的总结,不要错
开启SQLSERVER数据库缓存依赖优化网站性能
uniapp/H5 获取手机桌面壁纸 (静态壁纸)
[前端] DNS解析与优化
为什么在js中需要添加addEventListener()?
JS模块化系统
js通过Object.defineProperty() 定义和控制对象
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比