import pandas as pd
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=DESKTOP-0LA566U\SQLEXPRESS;'
'Database=AdventureWorksDW2019;'
'Trusted_Connection=yes;')
database=['DatabaseLog', 'DimAccount']
cursor = conn.cursor()
for i in database:
cursor.execute('SELECT * FROM database')
print(I)
df = pd.DataFrame(sql_query)
df.to_csv (r'C:\Users\cdtpr\OneDrive\Desktop\connections\database.csv', index = False)
getting error as below
PS C:\Users\cdtpr\OneDrive\Desktop\connections> & C:/Users/cdtpr/AppData/Local/Programs/Python/Python311/python
.exe "c:/Users/cdtpr/OneDrive/Desktop/connections/import pandas as pd.py"
now
45 mins
Traceback (most recent call last): File "c:\Users\cdtpr\OneDrive\Desktop\connections\import pandas as pd.py", line 14, in <module> cursor.execute('SELECT FROM database')
55 mins
57 mins
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax r the keyword 'database'. (156) (SQLExecDirect)") nea
59 mins
PS C:\Users\cdtpr\OneDrive\Desktop\connections>
1条答案
按热度按时间ccrfmcuu1#
首先使用此查询加载DataFrame
select schema_name(schema_id) schema_name, name table_name from sys.tables
然后循环访问中的行,构造如下查询
sql = f"select * from [{schemaName}].[{tableName}]"
表格中。