W
W
Workguy2020-12-27 21:30:45
Python
Workguy, 2020-12-27 21:30:45

Validation in sqlite3?

The question is to check for the existence of a given record in the database. I write as in the documentation, I did a little debugging, but anyway, when I try to add an existing entry to the database, it is successfully added ... Here is the code itself:

import sqlite3

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

sql.execute("""create table if not exists players(
   nick text,
   score integer
)""")
db.commit()

nick = input()
score = int(input())

sql.execute("select nick from players where nick = '{nick}'")
select = sql.fetchone()

if select is None:
   sql.execute(f'insert into players(nick, score) values (?, ?)', (nick, score))
   db.commit()

   print('Successfully done!')
else:
   print('Sorry...')

for value in sql.execute('select * from players'):
   print(value)


I beg you to help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2020-12-27
@SoreMix

I don’t know what documentation you read, but in the official select query looks clearly different:

t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)

put? as a placeholder wherever you want to use a value, and then provide a tuple of values ​​as the second argument to the cursor's execute() method. (Other database modules may use a different placeholder, such as %s or :1.) For example:

If everything is done as in the documentation:
sql.execute("select nick from players where nick = ?", (nick,))

then everything works great

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question