Erlon Dantas
Erlon Dantas

Reputation: 3

sqlite3.OperationalError: near " ": syntax error

Hi all right with you? I hope so, so I'm developing a commercial application, however this is giving an error in sql where it speaks: sqlite3.OperationalError: near "José": syntax error as if there was an error in the blank space of the phrase

cursor.execute(f"""update funcionarios
            set nome = {nome}, senha = {senha}, telefone = {telefone},
                endereco = {endereco}, anotacoes = {anotacao}
            where cpf = {pesq}
            """)

Name "ErlonJunior" without spaces works, but "José Street" with space returns this error:

 (IMAGE) Name "ErlonJunior" without spaces works, but "José Street" with space returns this error

Error sqlite3.OperationalError: near "José": syntax error:

 (IMAGE) Error sqlite3.OperationalError: near "José": syntax error

Upvotes: 0

Views: 3133

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195408

Don't format your SQL string by hand (in your case with f-strings), it's error prone. You could use parameterized queries in SQLite3:

import sqlite3

with sqlite3.connect(":memory:") as con:

    cur = con.cursor()

    cur.execute('CREATE TABLE funcionarios (id integer PRIMARY KEY, nome text)')

    cur.execute('INSERT INTO funcionarios (nome) VALUES (:nome)',
      {'nome': 'Rua Jose'})

    cur.execute('UPDATE funcionarios SET nome = :nome WHERE id = 1',
      {'nome': 'Santa Maria'})

    cur.execute('SELECT * FROM funcionarios')
    print(cur.fetchall())

This prints:

[(1, 'Santa Maria')]

Upvotes: 2

Related Questions