【问题标题】:How to run a SQL command with python?如何使用 python 运行 SQL 命令?
【发布时间】:2017-08-20 15:34:10
【问题描述】:

我想连接到 MS SQL Server 并使用 python 执行 SQL 命令。我熟悉使用 SQLAlchemy 创建 SQL 表、pandas DataFrames 等,但是如何使用 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 test.dbo.jobs
insert into dev.dbo.workers select * from test.dbo.workers

【问题讨论】:

标签: python sql sql-server pandas sqlalchemy


【解决方案1】:

您可以使用 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()

【讨论】:

  • 我需要关闭此连接还是它会自行关闭?
  • 如果您已经使用完连接,最好关闭它以便将其释放到池中。我将更新示例。
猜你喜欢
  • 1970-01-01
  • 2014-06-01
  • 2019-01-03
  • 2019-06-28
  • 2013-12-30
  • 1970-01-01
  • 2020-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多