P
P
Pavel2021-06-18 10:29:39
Python
Pavel, 2021-06-18 10:29:39

Why doesn't the INSERT INTO command work in my code?

Hello, Adding to the sqlite3 database does not work, the "Create_Account" function requires a username, username and password, but after execution (no errors) nothing is added, this is shown by a separate function for checking a specific username in the table and also print(all username from the table) after adding to the database function.

(I read a solution on many forums, but people forget to put commit() there, I have it right after INSERT INTO, but this line didn’t seem to exist, depending on what the database shows.)

(I probably understand that the code does not look very professional, I hope it will not be difficult to figure it out)

I will be glad even if there are just links to the documentation that you need to read, thanks)

import sqlite3

db = 0
cursor = 0

def AnalizInfo(): 
  global db, cursor

  db = sqlite3.connect('users.db', check_same_thread=False) #Создание базы данных или соединение
  cursor = db.cursor() #Создание курсора для базы

  #---Создать таблицу в базе
  cursor.execute("""CREATE TABLE IF NOT EXISTS users(
      name TEXT,
      username TEXT,
      password TEXT
    )""")

    #username, password - данные пользователей
                #name - имя пользователя
  db.commit()
  #---/////


  #/////



  #---Заполнение первого пользователя, если пользователей не найдено


        #Первое создание элемента при создании таблицы, только эти строки работают почему-то.
  if cursor.execute(f"SELECT username FROM users").fetchone() == None: #Если пользователей не найдено
    cursor.execute(f'INSERT INTO users VALUES (?, ?, ?)', ('Павел', 'Markus', 'Pvl0083777'))
    db.commit()


  #---////////



def Create_Account(name, username, password):
  global db, cursor
  if username in cursor.execute(f"SELECT username FROM users").fetchone(): #Если такой пользователь уже есть
    return 'Такой пользователь уже существует !'
  else:

    try:
                        #Две строки ниже не работают, по какой-то причине(вопрос про них в целом):
      cursor.execute(f'INSERT INTO users VALUES (?, ?, ?)', (name, username, password))
      db.commit()
                        #После этого идёт показ всех username из таблицы users, куда и добавлялся элемент, но он показывает, что добавился только первый элемент при создании базы.
      print(cursor.execute(f"SELECT username FROM users").fetchone()) #Вывести в консоль всю таблицу с username-ми
      return True


    except:
      return False




def main(username, password, types, name=None):
  AnalizInfo() #Первая функция для соединения или создание БД
  if types == 'Check_Account': #Если нужно проверить аккаунт
    return Check_Account(username, password)
  elif types == 'Create_Account': #Если нужно создать аккаунт
    return Create_Account(name, username, password)




print(main('Markus1', 'Pvl0083777', 'Create_Account'))

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
o5a, 2021-06-18
@Markus_Sinday

The add command itself works. But
1. Checking the presence of a user in the database is wrong. Can it be like this

if cursor.execute(f"SELECT username FROM users WHERE username = ?", (username, )).fetchone(): #Если такой пользователь уже есть

2. fetchone returns only the first record, so you don't see the rest when displaying "the entire table with usernames", there is fetchall.
3. It is better not to extinguish exceptions at all, otherwise there will be "no errors, but nothing works." It is better to display or log them.
except Exception as e:
    print('ошибка:', e)
    return False

G
galaxy, 2021-06-18
@galaxy

#After that, it shows all usernames from the users table, where the element was added, but it shows that only the first element was added when the database was created.
print(cursor.execute(f"SELECT username FROM users").fetchone()) #Print the entire table with usernames to the console
return True

What makes you think that this is "showing all usernames from the users table"?
Does the name of the fetch one () method suggest anything?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question