python - 如何使用列获取数据类型并创建字典
问题描述
Mysql 表student
有 2 个表students
和teach
代码如下
def tbl_col_names(table):
db = {}
for i in table:
cursor.execute("select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME= '%s'" % (i))
tabledescription = cursor.fetchall()
print ('tableDesc1', tabledescription)
tableDescription1 = [i[0] for i in tabledescription]
print (tableDescription1)
db[i] = tableDescription1
with open('data.json','w') as f:
db1 = json.dumps(db)
test = (f"data ='[{db1}]'")
f.write(test)
return db
cursor.execute("SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' AND table_schema='databasename'")
ecords = cursor.fetchall()
print (records)
member = [i[0] for i in records]
print ('member',member)
allcolumnvalues = tbl_col_names(member)
print ('all',allcolumnvalues )
data.json 输出如下
data = '[{"students": ["student_no"], "teach": ["last_name", "course_no"]}]'
如何获取数据类型以及列名
下面是获取列名和数据类型的mysql查询
select COLUMN_NAME,DATA_TYPE from INFORMATION_SCHEMA.COLUMNS where table_name='student';
cursor.execute("select COLUMN_NAME,DATA_TYPE from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME= '%s'" % (i))
我的预期结果data.json
如下
data = '[{"students": {"student_no":"int"}, "teach": {"last_name":"varchar", "course_no":"int"}}]'
解决方案
cursor.execute('show columns from databasename.students')
records = cursor.fetchall()
d = {record[0]: record[1] for record in records}
# or d = {record['Field']: record['Type'] for record in records} if the cursor.execute returns a dictionary
这将返回每个字段类型的详细描述,包括精度,例如int(11)
or varchar(32)
。如果您不希望包含精度,则:
d = {record[0]: record[1].split('(')[0] for record in records}
对于您感兴趣的每个数据库/表,您可以将如上例中计算的字典附加到列表中,以获得所需的结果:
def get_table_attributes(cursor, database, table):
cursor.execute(f'show columns from {database}.{table}')
records = cursor.fetchall()
return {record[0]: record[1] for record in records}
# return {record[0]: record[1].split('(')[0] for record in records}
data = []
data.append({'students': get_table_attributes(cursor, 'databasename', 'students')})
data.append({'teach': get_table_attributes(cursor, 'databasename', 'teach')})
推荐阅读
- css - 如何用 reactjs 创建这个 ui?
- json - 以前导 + 符号开头的整数的 JSON 解析错误,例如 +12345
- android - 视图绑定应该取代数据绑定吗?
- sql - OBIEE - 是否可以在 SELECT 语句中有子查询
- python - 检查单元格内容是屏幕上输入字符串的子字符串(包括退格) - python pandas
- python - 如何递归调用python中的函数将列表中的每个元素都放到底部?
- webrtc - 无法访问使用 coturn 构建的转弯服务器
- firebase - Firebase 扩展可以使用非官方扩展吗?
- c# - 如何在 C# 中在运行时创建一个类?我希望在我的文件系统中物理创建类
- python - 使用 docker 将回显输入发送到标准输入到 docker 容器