sqlobject:此线程或进程未定义连接

0 投票
1 回答
723 浏览
提问于 2025-04-15 23:42

我在Python中使用sqlobject库。我通过以下方式连接到数据库:

conn = connectionForURI(connStr)
conn.makeConnection()

这个连接成功了,我可以在这个连接上进行查询:

g_conn = conn.getConnection()
cur = g_conn.cursor()
cur.execute(query)
res = cur.fetchall()

这按预期工作。不过,我还定义了一些类,比如:

class User(SQLObject):
    class sqlmeta:
        table = "gui_user"
    username = StringCol(length=16, alternateID=True)
    password = StringCol(length=16)
    balance = FloatCol(default=0)

当我尝试使用这个类进行查询时:

User.selectBy(username="foo")

我遇到了一个异常:

...
  File "c:\python25\lib\site-packages\SQLObject-0.12.4-py2.5.egg\sqlobject\main.py", line 1371, in selectBy
    conn = connection or cls._connection
  File "c:\python25\lib\site-packages\SQLObject-0.12.4-py2.5.egg\sqlobject\dbconnection.py", line 837, in __get__
    return self.getConnection()
  File "c:\python25\lib\site-packages\SQLObject-0.12.4-py2.5.egg\sqlobject\dbconnection.py", line 850, in getConnection
    "No connection has been defined for this thread "
AttributeError: No connection has been defined for this thread or process

我该如何为一个线程定义连接呢?我刚意识到我可以传递一个connection关键字,这样我就可以把conn传进去让它工作,但如果我不这样做,怎么才能让它正常工作呢?

1 个回答

3

做:

from sqlobject import sqlhub, connectionForURI

sqlhub.processConnection = connectionForURI(connStr)

撰写回答