mysql与csv的python连通性

2024-09-25 02:38:31 发布

您现在位置:Python中文网/ 问答频道 /正文

“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)

Tags: textimportexecuteresultconnqueryyearcursor
2条回答

如果我理解正确,您只有一个表需要年份列,因此假设yeartable将是该表的名称

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)
     if (i == 'yeartable'):
         query=('select text, imdburl, year from %s '%(i))
     else:
         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)

对于可扩展的解决方案,您需要在表中获得一些信息
您可以获取表的所有列名,如下所示:

SELECT `COLUMN_NAME` 
FROM `INFORMATION_SCHEMA`.`COLUMNS` 
WHERE `TABLE_SCHEMA`='yourdatabasename' 
AND `TABLE_NAME`='yourtablename';

从上面的if中检查名为year的列,而不是检查yeartable,这样应该很好

这在python 3.8.5下运行 它将第二个查询包含在try中,除非case没有年份列,然后使用outyear刷新查询

您应该考虑调用不同的CSV,如果有多个CSV也是不同的

import pandas as pd
import pymysql
conn=pymysql.connect(host="localhost",user="root",password="testpawwd",db="bulkb1")
cursor=conn.cursor()
cursor.execute("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'bulk'")
myresult=cursor.fetchall()
for i in myresult:
    print(i)
    query=('select  text, imdburl, `year` from %s '%(i))
    query2=('select  text, imdburl from %s '%(i))
    try:
        cursor.execute(query)
        result=cursor.fetchall()
        print(result)
        my=pd.read_sql_query(query,conn)
        my.to_csv("new%s.csv"%(i),index=False)
        break
    except:
        try:
            cursor.execute(query2)
            result=cursor.fetchall()
            print(result)
            my=pd.read_sql_query(query2,conn)
            my.to_csv("new%s.csv"%(i),index=False)
            break
        except:
            print("An error occured")

相关问题 更多 >