![](/img/trans.png)
[英]How to insert a pandas dataframe into an existing postgres sql database?
[英]how to insert dataframe into SQl server database in pandas
我想將 dataframe 中的整行插入 pandas 中的 sql 服務器。
我可以使用下面的命令插入,但是,我有 46 多列並且不想鍵入所有 46 列。
server = 'server'
database = 'db'
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database)
cursor = cnxn.cursor()
for index, row in df.iterrows():
cursor.execute("INSERT INTO HumanResources.DepartmentTest (DepartmentID,Name,GroupName) values(?,?,?)", row.DepartmentID, row.Name, row.GroupName)
cnxn.commit()
cursor.close()
有沒有一種方法可以在不提供列名的情況下插入整行? 是這樣的嗎?
insert into table1
select * from df
我嘗試了以下命令,但失敗了,
for index, row in df.iterrows():
cursor.execute("INSERT INTO dbo.Staging select row"
)
Error:('42S22', "[42S22] [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column name 'row'. (207) (SQLExecDirectW); [42S22] [Microsoft][ODBC SQL Server Driver][SQL Server]Column name or number of supplied values does not match table definition. (213)")
我不能使用 to_sql,因為我不能在 UAT 或產品中導入 sqlalchemy。 誰能幫我這個?
與以下聲明一起提及列名稱
插入 table1 (col1,col2,...conN) select col1,col2,..colN 來自 df
忽略標識列
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.