sqlite3.OperationalError: near "example": syntax error in Python SQLite3

Question:
I was experimenting with SQLite3 and set up the connection for a database. When I ran the program to try to write to the database, I got this error:

I ignored the choices I selected and instead used the phrase ‘teststring’ to test the DB.
code snippet

import sqlite3 as db
connect = db.connect("relate.db")
def survey() :
  print("""
  Select an option:
  [1] Test
  [2] Foobar
  [3] MERT
  \n
  """)
  dns = input("")
  connect.execute(dns)
  connect.close()
survey()

LINK: https://replit.com/@Doomsdaybear/Find-Users-Like-You?v=1
I appreciate any help!

Hey, @anon45021817! It seems you are taking the variable dns and putting the value in the execute function of the SQLite3 database. SQLite’s execute function only takes valid SQL code like this

SELECT * FROM USERS

It does not take just numbers like

1 2 3

Here, I’ve fixed you code! :smiley:

import sqlite3 as db

# Establish a connection to the SQLite database
connect = db.connect("relate.db")

# Create a cursor to interact with the database
cursor = connect.cursor()

# Corrected the SQL query syntax to create a table named "TEST"
cursor.execute(
    """
CREATE TABLE IF NOT EXISTS TEST (
    id INTEGER PRIMARY KEY,
    name TEXT
)
"""
)


def survey():
    print(
        """
    Select an option:
    [1] Test
    [2] Foobar
    [3] MERT
    \n
    """
    )

    # Fixed potential SQL injection vulnerability by using parameterized queries
    option = input("")
    query = "INSERT INTO TEST (name) VALUES (?)"
    cursor.execute(query, (option,))

    # Commit the changes to the database
    connect.commit()

    # Close the database connection
    connect.close()


# Call the survey function
survey()

Enjoy!
-@LoganPaxton3

2 Likes