“text”和“imdburl”列在所有表格中都很常见,但当我添加年份时,“year”仅出现在一个表格中,它表示未知列“year”
有人能告诉我如何首先检查表中是否存在此列,然后添加它的add,否则只显示N\A
import pymysql
import pandas as pd
conn=pymysql.connect(host="localhost",user="root",password="",db="bulk")
cursor=conn.cursor()
cursor.execute("show tables")
myresult=cursor.fetchall()
for i in myresult:
print(i)
query=('select text,imdburl from %s '%(i))
cursor.execute(query)
result=cursor.fetchall()
print(result)
my=pd.read_sql_query(query,conn)
my.to_csv("new.csv",index=False)
如果我理解正确,您只有一个表需要年份列,因此假设
yeartable
将是该表的名称对于可扩展的解决方案,您需要在表中获得一些信息
您可以获取表的所有列名,如下所示:
从上面的
if
中检查名为year
的列,而不是检查yeartable
,这样应该很好这在python 3.8.5下运行 它将第二个查询包含在try中,除非case没有年份列,然后使用outyear刷新查询
您应该考虑调用不同的CSV,如果有多个CSV也是不同的
相关问题 更多 >
编程相关推荐