G
G
guit242021-11-29 23:41:34
Python
guit24, 2021-11-29 23:41:34

Problem with inserting arguments in python sql query, what is the reason?

The request is not sent. The code:

def register_command(command: str, user_id: int):
    time_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    with sq.connect('history.db') as con:
        cur = con.cursor()

        cur.execute("""
        INSERT INTO commands (user_id, date, command_name) VALUES (7 , {} , 'd')""".format(time_now))

Mistake:

line 38, in register_command
    cur.execute("""
sqlite3.OperationalError: near "23": syntax error
"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-11-30
@guit24

Do not under any circumstances do this

cur.execute("""INSERT INTO commands (user_id, date, command_name) VALUES (7 , {} , 'd')""".format(time_now))

You will catch SQL injection, and there will also be a lot of jambs with strings. You have already come across one.
It will be correct like this:
cur.execute("INSERT INTO commands (user_id, date, command_name) VALUES (7 , ?, 'd')", (time_now,))

In this case, the passed argument will be correctly escaped, wrapped in quotes, etc.
This is written at the beginning of the sqlite3 module documentation, but only losers read the documentation. it's true?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question