V
V
Vadimganin2022-04-02 11:14:53
SQLite
Vadimganin, 2022-04-02 11:14:53

Why does an error occur when registering a user in SQLite?

The code:

import sqlite3

db = sqlite3.connect('server.db')
sql = db.cursor()

sql.execute("""CREATE TABLE IF NOT EXISTS users (
  login TEXT,
  password TEXT,
  cash BIGINT
)""")

db.commit()

user_login = input('Login: ')
user_password = input('Password: ')

sql.execute("SELECT login FROM users")
if sql.fetchone() is None:
   sql.execute(f"INSERT INTO users VALUES (?, ?, ?)", (user_login, user_password, 0))
   db.commit()
else:
  print('No!')


Mistake:
Traceback (most recent call last):
  File "C:\Users\1\Desktop\learn\learn_sqlite\main.py", line 19, in <module>
    sql.execute(f"INSERT INTO users VALUES (?, ?, ?)", (user_login, user_password, 0))
sqlite3.OperationalError: table users has 4 columns but 3 values were supplied
PS C:\Users\1\Desktop\learn\learn_sqlite>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Nesterov, 2022-04-02
@AlexNest

1. As mentioned above and in the comments - the problem is in the table (apparently they already created it before, because everything works with the new database.)
2. Mistake # 2, a little less obvious, but also stupid. Specifically, in this form, the code in the block ifwill work only once.

sql.execute("SELECT login FROM users")
if sql.fetchone() is None:

T
TheAndrey7, 2022-04-02
@TheAndrey7

In an INSERT query, it is highly desirable to list the names of the fields so that the database does not guess what to assign where.

INSERT INTO users (login, password, cash) VALUES (?, ?, ?)

cash can be omitted if it is set to the default value at the table level.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question