28

Precursor:

MySQL Table created via:
CREATE TABLE table(Id INT PRIMARY KEY NOT NULL, Param1 VARCHAR(50))

Function:

.execute("INSERT INTO table VALUES(%d,%s)", (int(id), string)

Output:

TypeError: %d format: a number is required, not a str

I'm not sure what's going on here or why I am not able to execute the command. This is using MySQLdb in Python. .execute is performed on a cursor object.

EDIT:

The question: Python MySQLdb issues (TypeError: %d format: a number is required, not str) says that you must use %s for all fields. Why might this be? Why does this command work?

.execute("INSERT INTO table VALUES(%s,%s)", (int(id), string)
Matt Stokes
  • 3,762
  • 9
  • 23
  • 45
  • 1
    You are missing a `%` and `)` - `.execute("INSERT INTO table VALUES(%d,%s)"% (int(id), string))` – Hussain Dec 09 '13 at 05:08

4 Answers4

41

As the whole query needs to be in a string format while execution of query so %s should be used...

After query is executed integer value is retained.

So your line should be.

.execute("INSERT INTO table VALUES(%s,%s)", (int(id), string))

Explanation is here

ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83
noobmaster69
  • 2,396
  • 25
  • 40
  • I have received errors on python 2.7 with syntax like that. Atleast on my side if a parametized %s is expected my python expects a string value there, and I've had to convert it to string like str(someVal). – Kickass Mar 01 '18 at 22:33
  • @Kickass - You might want to check to see if you have a string interpolation operator (%) separating your SQL INSERT string and your values tuple instead of a comma. – Bob Kline Dec 28 '19 at 15:23
10

The format string is not really a normal Python format string. You must always use %s for all fields

lwzhuo
  • 194
  • 1
  • 5
0

I found a solution on dev.mysql.com. In short, use a dict, not a tuple in the second parameter of .execute():

add_salary = ("INSERT INTO salaries "
              "(emp_no, salary, from_date, to_date) "
              "VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")

data_salary = {
  'emp_no': emp_no,
  'salary': 50000,
  'from_date': tomorrow,
  'to_date': date(9999, 1, 1),
}

cursor.execute(add_salary, data_salary)
Andrea Corbellini
  • 15,400
  • 2
  • 45
  • 63
wyz
  • 1
-4

You missed a '%' in string formatting

"(INSERT INTO table VALUES(%d,%s)"%(int(id), string))
Arovit
  • 2,967
  • 5
  • 18
  • 23
  • 1
    i am sorry this s downvoted, but it is a way forward the answer `("INSERT INTO table VALUES(%d,'%s')"%(int(id), string))` you should edit it – Abr001am Apr 21 '17 at 14:57
  • Edited. Thanks. – Arovit Apr 22 '17 at 00:18
  • It's much safer to get in the habit of using the parameters to the `cursor.execute` function to eliminate risk of injection: https://stackoverflow.com/a/775399/6284025 – TallChuck Aug 11 '17 at 20:58