我可以在CherryPy中连接多个数据库吗?
cherrypy.engine
的 subscribe()
是一个用来连接数据库的功能,而这个 cherrypy.engine
的 start()
会在连接了那个数据库后启动。
如果我想从不同的数据库获取多组数据,我就需要连接到不同的数据库。
有没有什么方法可以在 CherryPy 中做到这一点,而不需要太多改动代码呢?
1 个回答
1
你需要使用两个游标,或者至少把同一个游标初始化两次。可以试试下面这样的做法...
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())
希望这能帮到你!