批量插入 SQL 服务器 Python 不工作
Bulk Insert into SQL Server with Python not working
我正在尝试将 csv 批量插入 SQL 服务器中的 table。问题是,数据与目标 table 的列不匹配。目标 table 有几个在源文件中找不到的审计列。我为此找到的解决方案是插入到视图中。代码非常简单:
from sqlalchemy import create_engine
engine = create_engine('mssql+pyodbc://[DNS]')
conn = engine.connect()
sql = "BULK INSERT [table view] FROM '[source file path]' WITH (FIELDTERMINATOR = ',',ROWTERMINATOR = '\n')"
conn.execute(sql)
conn.close()
当我 运行 SSMS 中的 SQL 语句时,它工作得很好。当我尝试从 Python 脚本中执行它时,脚本 运行s 但没有数据在 table 中结束。我错过了什么?
更新:事实证明批量插入普通 table 也不起作用。
事实证明,我不得不使用 pypyodbc,而不是使用 SQL Alchemy。不知道为什么这行得通而另一种方法行不通。此处的示例代码:
在关闭连接之前,您需要调用 commit() 否则 SQL 操作将在连接关闭时回滚。
conn.commit()
conn.close()
检查 sqlalchemy transactions refeference 后,这对我有用。我没有明确设置 conn.commit()
为
The block managed by each .begin() method has the behavior such that the transaction is committed when the block completes.
with engine.begin() as conn:
conn.execute(sql_bulk_insert)
我正在尝试将 csv 批量插入 SQL 服务器中的 table。问题是,数据与目标 table 的列不匹配。目标 table 有几个在源文件中找不到的审计列。我为此找到的解决方案是插入到视图中。代码非常简单:
from sqlalchemy import create_engine
engine = create_engine('mssql+pyodbc://[DNS]')
conn = engine.connect()
sql = "BULK INSERT [table view] FROM '[source file path]' WITH (FIELDTERMINATOR = ',',ROWTERMINATOR = '\n')"
conn.execute(sql)
conn.close()
当我 运行 SSMS 中的 SQL 语句时,它工作得很好。当我尝试从 Python 脚本中执行它时,脚本 运行s 但没有数据在 table 中结束。我错过了什么?
更新:事实证明批量插入普通 table 也不起作用。
事实证明,我不得不使用 pypyodbc,而不是使用 SQL Alchemy。不知道为什么这行得通而另一种方法行不通。此处的示例代码:
在关闭连接之前,您需要调用 commit() 否则 SQL 操作将在连接关闭时回滚。
conn.commit()
conn.close()
检查 sqlalchemy transactions refeference 后,这对我有用。我没有明确设置 conn.commit()
为
The block managed by each .begin() method has the behavior such that the transaction is committed when the block completes.
with engine.begin() as conn:
conn.execute(sql_bulk_insert)