我正在寻找创建一个临时表并将一些数据插入其中。我已经广泛使用pyodbc提取数据,但是我不熟悉从python环境将数据写入SQL的情况。我在工作时这样做,所以我没有创建表的能力,但是可以创建临时表和全局临时表。我的意图是在临时表中插入一个相对较小的数据帧(150rows x 4cols)并在整个会话中对其进行引用,我的程序结构使其无法在会话中使用全局变量。尝试时出现以下错误下面的那一块,我在做什么错了?
pyodbc.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)")
import numpy as np
import pandas as pd
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=SERVER;'
'Database=DATABASE;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
temp_creator = '''CREATE TABLE #rankings (Col1 int, Col2 int)'''
cursor.execute(temp_creator)
df_insert = pd.DataFrame({'Col1' : [1, 2, 3], 'Col2':[4,5,6]})
df_insert.to_sql(r'#rankings', conn, if_exists='append')
read_query = '''SELECT * FROM #rankings'''
df_back = pd.read_sql(read_query,conn)
答案 0 :(得分:1)
Pandas.to_sql在那里失败。但是对于SQL Server 2016 + / Azure SQL数据库,无论如何都存在更好的方法。不用让大熊猫插入每一行,而是将整个数据帧以JSON格式发送到服务器,然后将其插入到单个语句中。像这样:
[{"Col1":1,"Col2":4},{"Col1":2,"Col2":5},{"Col1":3,"Col2":6}]
Col1 Col2
0 1 4
1 2 5
2 3 6
Press any key to continue . . .
输出
calc()