Python ProgrammingError: 在一个线程中创建的 SQLite 对象只能在同一个线程中使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48218065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:36:20  来源:igfitidea点击:

ProgrammingError: SQLite objects created in a thread can only be used in that same thread

pythonmysqlsqliteflask

提问by Tania

i'm fairly new to programming. I've tried MySQL before, but now it's my first time using SQLite in a python flask website. So maybe I'm using MySQL syntax instead of SQLite, but I can't seem to find the problem.

我对编程还很陌生。我之前尝试过 MySQL,但现在是我第一次在 python Flask 网站中使用 SQLite。所以也许我使用的是 MySQL 语法而不是 SQLite,但我似乎找不到问题所在。

Piece of my code: 

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm(request.form)
    if request.method=='POST' and form.validate():
        name =  form.name.data 
        email = form.email.data
        username = form.username.data
        password = sha256_crypt.encrypt(str(form.password.data))

        c.execute("INSERT INTO users(name,email,username,password) 
        VALUES(?,?,?,?)", (name, email, username, password))

        conn.commit

        conn.close()

The error:
 File "C:\Users\app.py", line 59, in register c.execute("INSERT INTO users(name,email,username,password) VALUES(?,?,?,?)", (name, email, username, password))
 ProgrammingError: SQLite objects created in a thread can only be used in that 
 same thread.The object was created in thread id 23508 and this is thread id 
 22640

Does this mean I can't use the name, email username & password in an HTML file? How do I solve this?

这是否意味着我不能在 HTML 文件中使用名称、电子邮件用户名和密码?我该如何解决这个问题?

Thank you.

谢谢你。

采纳答案by ndrix

Your cursor 'c' is not created in the same thread; it was probably initialized when the Flask app was run.

您的光标 'c' 不是在同一个线程中创建的;它可能是在运行 Flask 应用程序时初始化的。

You probably want to generate SQLite objects (the conneciton, and the cursor) in the same method, such as:

您可能希望以相同的方法生成 SQLite 对象(连接和游标),例如:

  @app.route('/')
  def dostuff():
    with sql.connect("database.db") as con:
      name = "bob"
      cur = con.cursor()
      cur.execute("INSERT INTO students (name) VALUES (?)",(name))
      con.commit()
      msg = "Done"

回答by cmrussell

Where you make your connection to the database add the following.

在连接到数据库的地方添加以下内容。

conn = sqlite3.connect('your.db', check_same_thread=False)

回答by J J

engine = create_engine(
'sqlite:///restaurantmenu.db',
connect_args={'check_same_thread': False}
)

Works for me

为我工作

回答by ng10

In my case, I have the same issue with two python files creating sqlite engine and therefore possibly operating on different threads. Reading SQLAlchemy doc here, it seems it is better to use singleton technique in both files:

就我而言,我在创建 sqlite 引擎的两个 python 文件中遇到了同样的问题,因此可能在不同的线程上运行。在此处阅读 SQLAlchemy 文档,似乎在两个文件中都使用单例技术更好:

# maintain the same connection per thread
from sqlalchemy.pool import SingletonThreadPool
engine = create_engine('sqlite:///mydb.db',
                poolclass=SingletonThreadPool)

It does not solve all cases, meaning I occasionally getting the same error, but i can easily overcome it, refreshing the browser page. Since I'm only using this to debug my code, this is OK for me. For more permanent solution, should probably choose another database, like PostgreSQL or other database

它不能解决所有情况,这意味着我偶尔会遇到相同的错误,但我可以轻松克服它,刷新浏览器页面。因为我只用它来调试我的代码,所以这对我来说没问题。对于更永久的解决方案,应该选择另一个数据库,如 PostgreSQL 或其他数据库

回答by Asgar

You can try this:

你可以试试这个:

engine=create_engine('sqlite:///data.db', echo=True, connect_args={"check_same_thread": False})

It worked for me

它对我有用

回答by Mohamed Abdalla

I had the same problem and I fixed it by closing my connection after every call:

我遇到了同样的问题,我通过在每次通话后关闭连接来修复它:

results = session.query(something, something).all()
session.close()