我有我的代码在这里:
import pyodbc
import pandas as pd
cnxn_string = conn_str = pyodbc.connect(
'Driver=ODBC Driver 17 for SQL Server;'
'Server=server;'
'Database=db;'
'Trusted_Connection=yes;'
)
select_all_tables_query = pd.read_sql_query("""SELECT table_name
FROM information_schema.tables
WHERE table_type = 'BASE TABLE'""", cnxn_string)
tables = ['table1', 'table2']
for table in tables:
sql_query=pd.read_sql_query(f"SELECT * FROM {table}", cnxn_string)
df=pd.DataFrame(sql_query)
df.to_csv(r'C:\path\to\exported\file\location\{table}.csv', index=False)
它总是用列表中的最后一个表覆盖文件名。而且它只导出1个csv文件?我不知道为什么。当我运行它时,输出如下:
c:\path_to_python_file.py:19: UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested. Please consider using SQLAlchemy. sql_query=pd.read_sql_query(f"SELECT * FROM {table}", cnxn_string)
c:\path_to_python_file.py:19: UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested. Please consider using SQLAlchemy. sql_query=pd.read_sql_query(f"SELECT * FROM {table}", cnxn_string)
它不是每次迭代后选择每个表的名字,我不知道要给forloop加什么,所以它迭代每个表,然后写,然后再迭代。
1条答案
按热度按时间hc2pp10m1#
我想这样可能行得通:(无法访问数据等)
Using concat in pandas, click for the doc: