Can MySQLdb Connection and Cursor objects be safel

2019-08-10 03:38发布

问题:

I'm using mysqlclient v1.3.10 in Python 3.5. After connecting to the database, you get a connection object, from which you get a cursor object that you use to run your queries.

Are these objects thread safe (i.e. can I create one set and then share and use them between multiple different python threads)?

回答1:

It appears that you can't. The MySQLdb documentation states (scroll down a little further to threadsafety):

The general upshot of this is: Don’t share connections between threads. It’s really not worth your effort or mine, and in the end, will probably hurt performance, since the MySQL server runs a separate thread for each connection. You can certainly do things like cache connections in a pool, and give those connections to one thread at a time. If you let two threads use a connection simultaneously, the MySQL client library will probably upchuck and die. You have been warned.