python - python 3的数据库?

标签 python database python-3.x

我正在编写一小段服务器软件供多个用户个人使用。不是数百个,也不是数千个,但一次可能是 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 的任何其他数据库选项吗?

最佳答案

首先注意sqlite is thread safe

$ 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/

相关文章:

python - 使用 python lxml 获取 Excel xml 的父属性

python - 将一列时间戳转换为 pandas 中的句点

python - JupyterLab/Python/Pandas - 比较两个数据帧

mysql - 在 Yii2 中如何在 andFilterWhere() 方法中执行 sql 函数?或替代方法是什么?

Mysql - 访问同一服务器中不同位置的两个数据库

python - 无需安装即可使用 nltk

python - 按第二个值(或按总和)对 "Tuple"进行排序

python - 从 Python 中的 PDF 中提取带有字体详细信息(样式、大小、颜色、斜体等)的文本

java - 数据库表架构建议

python-3.x - 简单的 Python Web 服务器来保存文件