[英]Error while insert dataframe to Sql-server DB using to_sql function in python
I am trying to insert pandas dataframe df into SQL Server DB using dataframe.to_sql function. 我试图使用dataframe.to_sql函数将pandas dataframe df插入SQL Server DB。 But i getting below error:
但我得到以下错误:
Source code: 源代码:
import pyodbc
import sqlalchemy
import urllib
df #sample dataframe
params = urllib.parse.quote_plus("DRIVER={SQL Server};SERVER=GIRSQL.GIRCAPITAL.com;DATABASE=Tableau;UID=SQL_User;PWD=pass")
engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
engine.connect()
df.to_sql(name='[Tableau].[dbo].[Test table]',con=engine, index=False,
if_exists='append')
Error: 错误:
File "C:\\Users\\Arvinth\\sqlalchemy\\engine\\default.py", line 470, in do_execute cursor.execute(statement, parameters)
文件“C:\\ Users \\ Arvinth \\ sqlalchemy \\ engine \\ default.py”,第470行,在do_execute cursor.execute(语句,参数)中
sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'INTEGER'. (102) (SQLExecDirectW)") [SQL: '\\nCREATE TABLE [[Tableau].[dbo].[Test table]] (\\n\\t[A] INTEGER NULL, \\n\\t[B] INTEGER NULL, \\n\\t[C] INTEGER NULL\\n)\\n\\n']
sqlalchemy.exc.ProgrammingError:(pyodbc.ProgrammingError)('42000',“[42000] [Microsoft] [ODBC SQL Server驱动程序] [SQL Server]'INTEGER'附近的语法不正确。(102)(SQLExecDirectW)”)[SQL :'\\ n \\ nCREATE TABLE [[Tableau]。[dbo]。[Test table]](\\ n \\ t [A] INTEGER NULL,\\ n \\ t [B] INTEGER NULL,\\ n \\ t [C] INTEGER NULL \\ N)\\ n \\ n']
Sample dataframe: 示例数据帧:
A B C
0 0 0 0
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 6 6 6
7 7 7 7
Can anyone please help solve the issue. 任何人都可以帮助解决问题。
As commented, you referenced the database name and dbo
schema for table name arg in pandas' to_sql
call for '[Tableau].[dbo].[Test table]' and bracketed the names, rendering an error in the sqlAlchemy engine's CREATE TABLE
SQL call. 如上所述,您在pandas的
to_sql
调用'[Tableau]。[dbo]。[Test table]'中引用了表名 arg的数据库名称和dbo
模式,并将名称括起来,在sqlAlchemy引擎的CREATE TABLE
SQL中呈现错误呼叫。 Since the current connection is the referenced database and the default schema is dbo
, both qualifiers in name are not needed: `'[Tableau].[dbo]. 由于当前连接是引用的数据库而默认模式是
dbo
,因此不需要名称中的两个限定符: `'[Tableau]。[dbo]。 ' “
Hence, in df.to_sql
, simply reference the table name without bracket escaping: 因此,在
df.to_sql
,只需引用表名而不括号转义:
df.to_sql(name='Test table', con=engine, index=False, if_exists='append')
which will create the needed table in the default dbo
schema of the connected Tableau
database: 这将在连接的
Tableau
数据库的默认dbo
架构中创建所需的表:
CREATE TABLE [Test table] (
[A] INTEGER NULL,
[B] INTEGER NULL,
[C] INTEGER NULL
);
也许你可以在to_sql()
引用表:
df.to_sql('test_table',con=engine, index=False, if_exists='append')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.