1

i have a hopefully simple Problem with an SQL-command

Code:

c.execute("SELECT MAX(pic_num) FROM Pictures WHERE id = "+str(user_id))   

pic_num is a column in the database and user_id is an Integer in the database

I thought everything would be right but i get this Error:

sqlite3.OperationalError: near ")": syntax error

this Information doesn't help me at all

8
  • 1
    @PM77-1 bobby-tables.com Commented Feb 15, 2018 at 13:27
  • You should print the constructed query string as it is fed to execute(). Maybe user_id isn't what you expect. Commented Feb 15, 2018 at 13:28
  • 2
    Just to add, string concatenation when executing SQL queries is BAD and leaves you wide open for SQL injection. Check this page: docs.python.org/2/library/sqlite3.html. Most drivers allow you to pass args for string replacement which will sanitize first and prevent said SQL injection. Commented Feb 15, 2018 at 13:28
  • @brunodesthuilliers - Based on OP question, I do not believe he's ready to deal with SQL Injection. Commented Feb 15, 2018 at 13:28
  • I think the docs suggest this should be something like: c.execute("SELECT MAX(pic_num) FROM Pictures WHERE id = ?", str(user_id)) Commented Feb 15, 2018 at 13:29

3 Answers 3

2

The correct way to use python's db-api is to use placeholders in your SQL query and pass query values along, ie:

c.execute("SELECT MAX(pic_num) FROM Pictures WHERE id=?", [user_id,])   

Note that this might not necessarily solve your problem but since you didn't post the schema nor the user_id value we can't try & reproduce the issue.

Sign up to request clarification or add additional context in comments.

Comments

2

You should python sqlite module's substitution instead like so:

c.execute("SELECT MAX(pic_num) FROM Pictures WHERE id = ?", (user_id, ))

Comments

1

Thank you all for the fast answers!

c.execute("SELECT MAX(pic_num) FROM Pictures WHERE id = ?", (str(user_id), ))

this finally worked :)

I already have written some libs which should handle SQL-injection (they test the Input for quotes but you're right im very new with SQL :D)

1 Comment

Escaping the strings is worse than using place holders. The place holders don’t parse what they’re given as sql at all, it’s a single item.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.