简体   繁体   English

使用 Python 创建表并插入到 SQL 服务器

[英]Create table and Insert to SQL Server using Python

I have a huge table (147 columns) and I would like to know if it is possible to create the table in SQL server from my pandas dataframe so I don't have to CREATE TABLE for 147 columns.我有一个巨大的表(147 列),我想知道是否可以从我的 pandas dataframe 服务器中创建 SQL 服务器中的表,以便为 I147C55057DZ 列CREATE TABLE

I am trying to follow what is answered in most of related questions:我正在尝试遵循大多数相关问题的回答:

params = urllib.parse.quote_plus("DRIVER={ODBC Driver 17 for SQL Server};SERVER=DESKTOP-LFOSSEF;DATABASE=test;UID=xxxx;PWD=xxx")
engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
connection = engine.raw_connection()
df.to_sql("table_name", connection,index=False)

The user and password work because that's what I am using to sign in into sqlserver. userpassword有效,因为这是我用来登录 sqlserver 的。

When I run this, I get:当我运行它时,我得到:

Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name ' sqlite_master'。(208)(SQLExecDirectW);[42S02][Microsoft][ODBC Driver 17 for SQL 服务器][SQL Server]无法准备语句。(8180)“)

If I remove the connection = engine.raw_connection() and use engine directly, I get:如果我删除connection = engine.raw_connection()并直接使用engine ,我会得到:

AttributeError: 'Engine' object has no attribute 'cursor' AttributeError: 'Engine' object 没有属性 'cursor'

Any idea what is wrong?知道有什么问题吗? Do I need to create an empty table first?我需要先创建一个空表吗? I've been troubleshooting for hours and can't find any reason why this isnt working.我已经进行了几个小时的故障排除,找不到任何原因导致这不起作用。

Do it like this.像这样做。

import pyodbc

engine = "mssql+pyodbc://Your_Server_Name/Your_DB_Name?driver=SQL Server Native Client 11.0?trusted_connection=yes"

df.to_sql(x, engine, if_exists='append', index=True)

df = name of your dataframe & x = name of your table in SQL Server df = 您的 dataframe 的名称 & x = 您在 SQL 服务器中的表的名称

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

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