I'm definitely new to SQL but I feel like inserting is pretty simple. I can't figure out the issue
def insert(title, name):
time = datetime.now()
conn = sqlite3.connect('test.db')
c = conn.cursor()
query = """INSERT INTO test ('{}', '{}', '{}')""".format(title, name, time)
c.execute(query)
conn.commit()
When I pass the following:
insert(1, 2)
I get the error:
OperationalError: near "'1'": syntax error
All fields are text if that helps.
Thanks in advance
1 Answer 1
You have not properly formatted your insert statement.
Right now you're specifying column names in the parens. To specify values, you need to use the VALUES keyword. You don't have to specify column names if your providing values for all columns, but you do need to include VALUES.
Do not use string concatenation to build queries. Instead, use parameterized queries, which allows the database driver to escape any user input that could otherwise lead to an injection attack.
query = 'INSERT INTO test (title, name, time) VALUES (?, ?, ?)'
c.execute(query, (title, name, time))
format,%, etc; you're vulnerable to SQL injection. Use parameterized queries instead.c.execute("INSERT INTO test VALUES (?,?,?)", (title, name, time))