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

后端 未结 6 392
挽巷
挽巷 2020-12-01 04:58

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 o

相关标签:
6条回答
  • 2020-12-01 05:25

    You can try this:

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

    It worked for me

    0 讨论(0)
  • 2020-12-01 05:33

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

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

      @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"
    
    0 讨论(0)
  • 2020-12-01 05:39

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

    results = session.query(something, something).all()
    session.close()
    
    0 讨论(0)
  • 2020-12-01 05:43

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

    conn = sqlite3.connect('your.db', check_same_thread=False)
    
    0 讨论(0)
  • 2020-12-01 05:43
    engine = create_engine(
    'sqlite:///restaurantmenu.db',
    connect_args={'check_same_thread': False}
    )
    

    Works for me

    0 讨论(0)
  • 2020-12-01 05:43

    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:

    # 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

    0 讨论(0)
提交回复
热议问题