cherrypy.engine
subscribe()
是一个连接数据库的函数,这个cherrypy.engine
start()
订阅了该数据库。
如果我想从不同的数据库中获取多组数据,我需要连接到不同的数据库。
在没有太多代码更改的情况下,有没有办法在CherryPy中执行此操作?
答案 0 :(得分:1)
您需要使用2个游标或至少初始化相同的游标两次。尝试这样的事情......
import cherrypy
import MySQLdb
def connect(thread_index):
# Create a connection and store it in the current thread
cherrypy.thread_data.db = MySQLdb.connect('host', 'user', 'password', 'dbname')
cherrypy.thread_data.db2 = MySQLdb.connect('host', 'user', 'password', 'dbname2')
# Tell CherryPy to call "connect" for each thread, when it starts up
cherrypy.engine.subscribe('start_thread', connect)
class Root:
def index(self):
# Sample page that displays the number of records in "table"
# Open a cursor, using the DB connection for the current thread
c = cherrypy.thread_data.db.cursor()
c.execute('select count(*) from table')
res = c.fetchone()
c.close()
c = cherrypy.thread_data.db2.cursor()
c.execute('select count(*) from table2')
res = c.fetchone()
return "<html><body>Hello, you have %d records in your table</body></html>" % res[0]
index.exposed = True
cherrypy.quickstart(Root())
希望这有帮助!