简体   繁体   English

在SQLAlchemy Core中执行多个独立语句?

[英]Execute multiple independent statements in SQLAlchemy Core?

I'm using SQLAlchemy Core to run a few independent statements.我正在使用 SQLAlchemy Core 来运行一些独立的语句。 The statements are to separate tables and unrelated .语句是分开的表和不相关的。 Because of that I can't use the standard table.insert() with multiple dictionaries of params passed in. Right now, I'm doing this:因此,我不能将标准table.insert()与传入的多个参数字典一起使用。现在,我正在这样做:

sql_conn.execute(query1)
sql_conn.execute(query2)

Is there any way I can run these in one shot instead of needing two back-and-forths to the db?有什么方法可以一次性运行这些,而不是需要两次来回访问数据库? I'm on MySQL 5.7 and Python 2.7.11.我在 MySQL 5.7 和 Python 2.7.11 上。

It is neither wise, nor practical, to run two queries at once. 一次运行两个查询既不明智也不实际。

It is not wise allowing such give hackers another way to do nasty things via "SQL Injection". 让黑客以另一种方式通过“SQL注入”做出讨厌的事情是不明智的。

On the other hand, it is possible, but not necessarily practical. 另一方面,它是可能的,但不一定是实用的。 You would create a Stored Procedure that contains any number of related (or unrelated) queries in it. 您将创建一个存储过程,其中包含任意数量的相关(或不相关)查询。 Then CALL that procedure. 然后CALL那个程序。 There some things that may make it impractical: 有些事情可能会使它变得不切实际:

  • The only way to get data in is via a finite number of scalar arguments. 获取数据的唯一方法是通过有限数量的标量参数。
  • The output comes back as multiple resultsets; 输出返回多个结果集; you need to code differently to see what happened. 你需要用不同的代码来看看发生了什么。

Roundtrip latency is insignificant if you are on the same machine with the MySQL server. 如果您与MySQL服务器在同一台计算机上,则往返延迟是微不足道的 It can usually be ignored even if the two servers are in the same datacenter. 即使两台服务器位于同一数据中心,通常也可以忽略它。 Latency becomes important when the client and server are separated by a long distance. 当客户端和服务器长距离分开时,延迟变得很重要。 For cross-Atlantic latency, we are talking over 100ms. 对于跨大西洋延迟,我们谈论超过100毫秒。 Brazil to China is about 250ms. 巴西到中国的时间约为250毫秒。 (Be glad we are no living on Jupiter.) (很高兴我们没有住在木星上。)

Sounds like you want a Transaction :听起来你想要一个Transaction

with engine.connect() as sql_conn:
    with sql_conn.begin():
        sql_conn.execute(query1)
        sql_conn.execute(query2)

There is an implicit sql_conn.commit() above (when using the context manager) which commits the changes to the database in one trip.上面有一个隐式的sql_conn.commit() (使用上下文管理器时),它一次将更改提交到数据库。 If you want to do it explicitly, it's done like this:如果你想明确地这样做,它是这样完成的:

from sqlalchemy import create_engine
engine = create_engine("postgresql://scott:tiger@localhost/test")
connection = engine.connect()
trans = connection.begin()
connection.execute(text("insert into x (a, b) values (1, 2)"))
trans.commit()

https://docs.sqlalchemy.org/en/14/core/connections.html#basic-usage https://docs.sqlalchemy.org/en/14/core/connections.html#basic-usage

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

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