Skip to content
Advertisement

Sqlite3 Programming Error -> SQLite objects created in a thread can only be used in that same thread

Im programming for my friend a website like youtube.
But I always get this error when i go to http://localhost:2389/watch.v=f4efc9de771d4aba85ee0a88bbce08b9

This is the server code:

    @app.route('/watch.v=<VideoId>')
    def watch(VideoId):
return render_template(
    "video.html",
    VideoName=video.load_from_id(VideoId),
    VideoId=VideoId
)

and this is the database helper:

from sqlite3 import OperationalError
from qrcode import *
from pathlib import Path
import sqlite3
import os
import uuid

DEFAULT_PATH = (os.getcwd() + "\apidatabase.db")
connection = sqlite3.connect(DEFAULT_PATH)
cursor = connection.cursor()
cur = cursor


def generateID():
    return uuid.uuid4().hex


class video:
    def db():
        try:
            connection = sqlite3.connect(DEFAULT_PATH)
            cursor = connection.cursor()
            cursor.execute("CREATE TABLE video (name, videoID);")
            connection.commit()
            print("Creating Database in:", DEFAULT_PATH.upper())
            print("[+] Database successfull created!")

        except OperationalError:
            print("[*] Database allready exists!")
            
    def load_from_id(id):
            cursor.execute(f'SELECT name from video WHERE videoID="{id}"')
            v = cursor.fetchall()
            return str(v).replace("[", "").replace("]", "").replace("'", "").replace("(", "").replace(")", "").strip(",")
        
    class new:
        def newVideo(name):
            i = generateID()
            NewUserData = "INSERT INTO video (name, videoID) VALUES (?, ?)"
            cursor.execute(NewUserData, (name, i))
            connection.commit()
            print(f"[+] Video successfull ceated ({name}, {i}).")

if __name__ == "__main__":
    #video.db()
    #video.new.new("Test_01")
    n = video.load_from_id("f4efc9de771d4aba85ee0a88bbce08b9")
    print(n)

And this is the error:

        Traceback (most recent call last):
  File "C:UsersadminOneDriveDesktopyoutubeserver.py"
    cursor.execute(f'SELECT name from video WHERE videoID="{id}"')
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread.
                          The object was created in thread id 15232 and this is thread id 13568.        

I hope someone can help me.

Advertisement

Answer

I found the problem.
I have to do this:

    def load_from_id(id):
            try:
                cursor = connection.cursor()
                data = f'SELECT name from video WHERE videoID="{id}"'
                cursor.execute(data)
                v = cursor.fetchall()
                return str(v).replace("[", "").replace("]", "").replace("'", "").replace("(", "").replace(")", "").strip(",")

            except ProgrammingError as pe:
                print(pe)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement