如何使用python运行SQL命令?
我想连接到MS SQL Server并使用python执行SQL命令。我熟悉使用SQLAlchemy创建SQL表、pandas数据帧等,但是如何使用python/pandas/SQLAlchemy在.SQL文件中执行SQL?有更好的方法吗 例如,我有包含sql文本的文件“update.sql”:如何使用python运行SQL命令?,python,sql,sql-server,pandas,sqlalchemy,Python,Sql,Sql Server,Pandas,Sqlalchemy,我想连接到MS SQL Server并使用python执行SQL命令。我熟悉使用SQLAlchemy创建SQL表、pandas数据帧等,但是如何使用python/pandas/SQLAlchemy在.SQL文件中执行SQL?有更好的方法吗 例如,我有包含sql文本的文件“update.sql”: truncate table dev.dbo.jobs truncate table dev.dbo.workers go insert into dev.dbo.jobs select * from
truncate table dev.dbo.jobs
truncate table dev.dbo.workers
go
insert into dev.dbo.jobs select * from test.dbo.jobs
insert into dev.dbo.workers select * from test.dbo.workers
您可以使用SQLAlchemy的connection.execute来运行原始SQL查询。如果sql语句存储在一个文件中,那么它可能如下所示:
from sqlalchemy import create_engine
from sqlalchemy.sql import text
engine = create_engine('urltodb')
conn = engine.connect()
with open('file.sql', 'r') as f:
for l in f:
stmt = text(l)
conn.execute(stmt)
conn.close()
已回答-请查看我是否需要关闭此连接或它是否会自行关闭?如果您已完成使用该连接,最好将其关闭,以便将其释放到池中。我将更新示例。