14

我有一个连接到 MySQL 数据库的芹菜项目。其中一张表的定义如下:

class MyQueues(Base):
    __tablename__ = 'accepted_queues'

    id = sa.Column(sa.Integer, primary_key=True)
    customer = sa.Column(sa.String(length=50), nullable=False)
    accepted = sa.Column(sa.Boolean, default=True, nullable=False)
    denied = sa.Column(sa.Boolean, default=True, nullable=False)

另外,在我的设置中

THREADS = 4

我被困在一个函数中code.py

def load_accepted_queues(session, mode=None):

    #make query  
    pool = session.query(MyQueues.customer, MyQueues.accepted, MyQueues.denied)

    #filter conditions    
    if (mode == 'XXX'):
        pool = pool.filter_by(accepted=1)
    elif (mode == 'YYY'):
        pool = pool.filter_by(denied=1)
    elif (mode is None):
        pool = pool.filter(\
            sa.or_(MyQueues.accepted == 1, MyQueues.denied == 1)
            )

   #generate a dictionary with data
   for i in pool: #<---------- line 90 in the error
        l.update({i.customer: {'customer': i.customer, 'accepted': i.accepted, 'denied': i.denied}})

运行此程序时出现错误:

[20130626 115343] Traceback (most recent call last):
  File "/home/me/code/processing/helpers.py", line 129, in wrapper
    ret_value = func(session, *args, **kwargs)
  File "/home/me/code/processing/test.py", line 90, in load_accepted_queues
    for i in pool: #generate a dictionary with data
  File "/home/me/envs/me/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2341, in instances
    fetch = cursor.fetchall()
  File "/home/me/envs/me/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 3205, in fetchall
    l = self.process_rows(self._fetchall_impl())
  File "/home/me/envs/me/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 3174, in _fetchall_impl
    self._non_result()
  File "/home/me/envs/me/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 3179, in _non_result
    "This result object does not return rows. "
ResourceClosedError: This result object does not return rows. It has been closed automatically

所以主要是部分

ResourceClosedError: This result object does not return rows. It has been closed automatically

有时也会出现这个错误:

DBAPIError: (Error) (, AssertionError('Result length not requested length:\nExpected=1. Actual=0. Position: 21. Data Length: 21',)) 'SELECT accepted_queues.customer AS accepted_queues_customer,accepted_queues.accepted AS accepted_queues_accepted ,accepted_queues.denied AS accepted_queues_denied \nFROM accepted_queues \nWHERE accepted_queues.accepted = %s OR accepted_queues.denied = %s' (1, 1)

我无法正确重现错误,因为它通常在处理大量数据时发生。我尝试更改THREADS = 41,错误消失了。无论如何,这不是一个解决方案,因为我需要保持线程数4

另外,我对使用的需要感到困惑

for i in pool: #<---------- line 90 in the error

或者

for i in pool.all(): #<---------- line 90 in the error

并且找不到适当的解释。

一起来:有什么建议可以跳过这些困难吗?

4

3 回答 3

14

一起来:有什么建议可以跳过这些困难吗?

是的。您绝对不能同时在多个线程中使用 Session(或与该 Session 关联的任何对象)或 Connection,尤其是 MySQL-Python,其 DBAPI 连接非常不安全*。您必须组织您的应用程序,以便每个线程处理它自己的专用 MySQL-Python 连接(以及因此与该会话关联的 SQLAlchemy 连接/会话/对象),而不会泄漏到任何其他线程。

  • 编辑:或者,您可以使用互斥锁来限制对 Session/Connection/DBAPI 连接的访问​​一次只能访问其中一个线程,尽管这种情况不太常见,因为所需的高度锁定往往会破坏使用的目的首先是多个线程。
于 2013-06-27T16:20:49.767 回答
2

我在SQL-Server使用SQLAlchemy. 就我而言,添加SET NOCOUNT ON到存储过程可以解决问题。

ALTER PROCEDURE your_procedure_name
AS
BEGIN

    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for your procedure here
    SELECT *
    FROM your_table_name;

END;

查看这篇文章了解更多详情

于 2021-08-01T07:55:07.270 回答
0

当我variable在 Python 中使用 a 并 使用 pandas
的语句解析它时,我发生了这个错误UPDATEpd.read_sql()

解决方案:

我只是使用mycursor.execute()而不是pd.read_sql()

import mysql.connectorfrom sqlalchemy import create_engine

前:

pd.read_sql("UPDATE table SET column = 1 WHERE column = '%s'" % variable, dbConnection)

后:

mycursor.execute("UPDATE table SET column = 1 WHERE column = '%s'" % variable)

完整代码:

import mysql.connector
from sqlalchemy import create_engine
import pandas as pd


# Database Connection Setup >
sqlEngine = create_engine('mysql+pymysql://root:root@localhost/db name')
dbConnection = sqlEngine.connect()

db = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="root",
    database="db name")

mycursor = db.cursor()

variable = "Alex"
mycursor.execute("UPDATE table SET column = 1 WHERE column = '%s'" % variable)
于 2021-05-20T12:04:25.027 回答