简体   繁体   English

将 Pandas 数据框插入 SQL 临时表

[英]Insert pandas data frame into SQL temp table

I am attempting to great a temporary table in an SQL database and populate the table from a pandas dataframe.我正在尝试在 SQL 数据库中创建一个临时表并从 Pandas 数据框中填充该表。 I am receiving an error when using the df.to_sql to populate the temp table.使用 df.to_sql 填充临时表时收到错误。 Thank you for the assistance.感谢您的帮助。

import pandas as pd
from sqlalchemy import create_engine
import pandas.io.sql as psql
import urllib

params = urllib.quote_plus("DRIVER={SQL Server};SERVER=ServerAddressHere;DATABASE=DatabaseNameHere;Trusted_Connection=yes")

engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
connection = engine.connect()
resoverall = connection.execute('''SELECT DISTINCT
a.CountryRegionID AS ISO_Short,
b.Name
FROM
CustTable AS a
LEFT JOIN AddressCountryRegion AS b
ON b.CountryRegionID = a.CountryRegionID''')


Countries= pd.DataFrame(resoverall.fetchall())
Countries.columns = resoverall.keys()

Countries= pd.Countries['ISO_Short'].str.upper()

Countries= pd.DataFrame(data=Countries)

temp = connection.execute('''
create table #tempTable
(
ISO_Short varchar(5)
)
''')

Countries.to_sql('Countries',engine)

The error I'm receiving is:我收到的错误是:

ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]CREATE TABLE permission denied in database 'databasename'. (262) (SQLExecDirectW)") [SQL: u'\\nCREATE TABLE [Countries] (\\n\\t[index] BIGINT NULL, \\n\\t[ISO_Short] VARCHAR(max) NULL\\n)\\n\\n' ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]CREATE TABLE 权限在数据库 'databasename' 中被拒绝。(262) (SQLExecDirectW)") [SQL: u'\\nCREATE TABLE [Countries] (\\n\\t[index] BIGINT NULL,\\n\\t[ISO_Short] VARCHAR(max) NULL\\n)\\n\\n'

UPDATE:更新:

The other option I thought of is to use Pyodbc and convert Countries to a dictionary and then pass the dictionary values into the temporary table.我想到的另一个选择是使用 Pyodbc 并将国家转换为字典,然后将字典值传递到临时表中。 Using this method, everything works until I try and pass the dictionary to the temp table.使用这种方法,一切正常,直到我尝试将字典传递给临时表。 I have the following code using this approach:我有使用这种方法的以下代码:

import pandas as pd
import pyodbc
import pandas.io.sql as psql

cnxn = pyodbc.connect('''DRIVER={SQL Server};SERVER=telsmith;
DATABASE=DatabaseNameHere;Trusted_Connection=yes;''')
cursor = cnxn.cursor()

Countries= '''
SELECT DISTINCT
a.CountryRegionID AS ISO_Short,
b.Name
FROM
CustTable AS a
LEFT JOIN AddressCountryRegion AS b
ON b.CountryRegionID = a.CountryRegionID
'''

Countries= psql.read_sql(Countries, cnxn)


Countries= Countries['ISO_Short'].str.upper()

Countries= pd.DataFrame(data=Countries)

Countriesdict = Countries.to_dict()


Temp = '''
create table #tempTable
(
    ISO_Short varchar(5)
)

'''

cnxn.commit()

# This is where I run into difficulty
placeholders = ', '.join(['%s'] * len(Countriesdict ))
columns = ', '.join(Countriesdict .keys())
sql = "INSERT INTO #tempTable VALUES ( %s )" % (placeholders)
cursor.execute(sql, Countriesdict.values())

This might sound little dumb but look at the error:这可能听起来有点愚蠢,但看看错误:

ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]CREATE TABLE permission denied in database 'databasename'. (262) (SQLExecDirectW)") [SQL: u'\\nCREATE TABLE [Countries] (\\n\\t[index] BIGINT NULL, \\n\\t[ISO_Short] VARCHAR(max) NULL\\n)\\n\\n' ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]CREATE TABLE 权限在数据库 'databasename' 中被拒绝。(262) (SQLExecDirectW)") [SQL: u'\\nCREATE TABLE [Countries] (\\n\\t[index] BIGINT NULL,\\n\\t[ISO_Short] VARCHAR(max) NULL\\n)\\n\\n'

Do you have any database called databasename ?你有任何名为databasename吗? Since It can't find database, it can't create table.由于找不到数据库,因此无法创建表。 I ran the same code and it worked just fine.我运行了相同的代码,它工作得很好。 I believe that's the reason我相信这就是原因

Not strictly a SQLAlchemy concern.不是严格意义上的 SQLAlchemy 问题。 You need to obtain "CREATE TABLE" permissions on the server from your DBA for some username and password, and use those credentials to access your DB.您需要从 DBA 获取服务器上的“CREATE TABLE”权限以获取某些用户名和密码,并使用这些凭据访问您的数据库。 Try including "UID=uname;PWD=pword;"尝试包括“UID=uname;PWD=pword;” in your params for some set of permissioned credentials.在您的参数中获取一些许可凭据。

I might have a solution that worked for me:我可能有一个对我有用的解决方案:

from sqlalchemy import create_engine
import urllib
params = urllib.parse.quote_plus("DRIVER={SQL Server};SERVER=10.233.6.52;DATABASE=databaseName;UID=xxx;PWD=Welcome1!")

engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
connection = engine.connect()
df.to_sql('tempTable',engine)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM