F
F
Frayl2021-05-01 11:03:56
Python
Frayl, 2021-05-01 11:03:56

How to fix error in sqlite?

I have some code that queries sqlite and connects to it. I ran into a problem that the data from the db is deleted after the script is restarted, how can I fix this?

Here is the code:

import sqlite3

try:
    with open("users.db", "r") as data:
        data.close()
except FileNotFoundError:
    with open("users.db", "w") as data:
        data.close()

con = sqlite3.connect("users.db")


def create_Table():
    cursor = con.cursor()
    cursor.execute("CREATE TABLE IF NOT EXISTS users (user_name TEXT NOT NULL, user_surname TEXT NOT NULL, user_id INTEGER NOT NULL, date TEXT NOT NULL);")

    del cursor


def exists_User(user_id):
    cursor = con.cursor()
    result = cursor.execute("SELECT * FROM users WHERE user_id = ?", (user_id, ))

    for row in result.fetchall():
        if len(row) > 0:
            return True
        else:
            return False

    del cursor


def create_User(user_id, user_name, user_surname):
    cursor = con.cursor()
    cursor.execute("INSERT INTO users (user_id, user_name, user_surname, date) VALUES (?, ?, ?, ?)", (user_id, user_name, user_surname, datetime.datetime.now().strftime("%d-%m-%Y %H:%M")))

    del cursor


def get_UserDate(user_id):
    cursor = con.cursor()
    result = cursor.execute("SELECT date FROM users WHERE user_id = ?", (user_id, ))

    for row in result.fetchall():
        return row[0]

    del cursor

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan., 2021-05-01
@LaRN

Most likely this is because you do not commit the changes by calling the
cursor.commit () function.
And in the exists_User and get_UserDate functions, the exit occurs before the del cursor, but this does not apply to the question asked.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question