1

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

asked May 8, 2015 at 1:27
1
  • 2
    Don't pass in parameters to queries using string concatenation, format, %, etc; you're vulnerable to SQL injection. Use parameterized queries instead. c.execute("INSERT INTO test VALUES (?,?,?)", (title, name, time)) Commented May 8, 2015 at 1:33

1 Answer 1

4

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))
davidism
128k31 gold badges417 silver badges348 bronze badges
answered May 8, 2015 at 1:34
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.