sqlobject:没有为此线程或进程定义任何连接

时间:2010-06-08 20:11:45

标签: python sql sqlobject

我在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 个答案:

答案 0 :(得分:3)

执行:

from sqlobject import sqlhub, connectionForURI

sqlhub.processConnection = connectionForURI(connStr)