我正在编写一小段服务器软件供多个用户个人使用。不是数百个,也不是数千个,但一次可能是 3-10 个。
因为它是一个线程服务器,SQLite 不工作。它提示这样的线程:
ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 140735085562848 and this is thread id 4301299712
此外,他们说 SQLite 无论如何都不适合并发。
现在,自从我开始使用 Python 3(并且宁愿继续使用它)以来,我似乎无法让 MySQL 模块正常工作,其他人似乎同样感到沮丧。
在那种情况下,我可以考虑使用 Python 3 的任何其他数据库选项吗?
最佳答案
$ python
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
>>> sqlite.threadsafety
1
然后确保在每个线程中打开一个新的数据库句柄。
我使用线程本地存储来缓存数据库句柄,因此每个线程只有一个。像这样的...(来自 py2.5 prog - 希望它能与 3.0 一起使用!)
import threading
class YourClass:
def __init__(self):
#...
self.local = threading.local() # Thread local storage for db handles
self.db_file = "/path/to/db"
#...
def db_open(self):
if not getattr(self.local, "db", None):
self.local.db = sqlite3.connect(self.db_file)
return self.local.db
关于python - python 3的数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1547365/