使用dataframe将所有sql表导入python

2024-06-26 10:52:14 发布

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

我需要将sql数据库中存储的所有表导入python。我已经成功地为它创建了一个python代码,如下所示:

^{pr 1}$

使用此功能,我能够成功地将表数据导入到数据框中

但是从数据库模式中可以看出,有多个表,这些表将来还会增加

Full database schema along with output of the table

数据帧看起来像:

Imported table from sql converted to DataFrame

是否有任何方法可以使用循环或通过任何其他方法为给定数据库中的所有表自动生成此脚本

我提到以下几点:

Importing multiple SQL tables using pandas

但这在我的情况下不起作用

谢谢


Tags: 数据方法代码功能数据库outputsqlschema
1条回答
网友
1楼 · 发布于 2024-06-26 10:52:14

SQL错误来自“表名周围,这不是最好的,但如果您使用的是本地应用程序,则可以使用f字符串:

with connection.cursor() as pointer:
    pointer.execute("use use stock")
    pointer.execute("SHOW TABLES")

    tables_tuples=[]
    for table_dict in pointer:
        for k,v in table_dict.items():
            tables_tuples.append(v)


for tables_name in tables_tuples:
    with connection.cursor() as pointer:
    
        #pointer.execute(f"SELECT * FROM %s",tables_name)
        pointer.execute(f"SELECT * FROM {tables_name}")
        
        connection.commit()


        df=pd.DataFrame(pointer)
        print(df)

相关问题 更多 >