Mahesh Jaganiya
Mahesh Jaganiya

Reputation: 165

Error "not all arguments converted during string formatting" while inserting in Database MySQL

I have an SQL query which is giving an error:

cur.execute("INSERT INTO `DB` (`ban`, `dntr`, `usrnm`, `id`, `dis`)  VALUES (1,0,?,?,?)",(param1,param2,param3,))

I don't want to use %s in query because it is prone to SQL injection and I am taking input from users.

Upvotes: 1

Views: 58

Answers (1)

Alasdair
Alasdair

Reputation: 308889

mysqlclient uses %s as the placeholder (see the example in the docs).

Change your code to the following:

cur.execute("INSERT INTO `DB` (`ban`, `dntr`, `usrnm`, `id`, `dis`)  VALUES (1,0,%s,%s,%s)", (param1,param2,param3,))

You're right to be concerned about SQL injection, but the above is OK. You are still using execute with parameters, so they will be escaped.

The thing you shouldn't do is cur.execute(query % parameters, []). This is vulnerable to SQL injection.

Upvotes: 2

Related Questions