Kai H.
Kai H.

Reputation: 39

mysqldb query: not enough arguments for format string

curs.execute ("INSERT INTO temperatur (datum, uhrzeit, ort, messwert) VALUES (CURRENT_DATE(), NOW(), %s, %s);" % ort, messwert)

drops out this->

    curs.execute ("INSERT INTO temperatur (datum, uhrzeit, ort, messwert) VALUES (CURRENT_DATE(), NOW(), %s, %s);" % ort, messwert)
TypeError: not enough arguments for format string

why is this not working?

Upvotes: 0

Views: 2767

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121644

Do not use string formatting, you are exposing yourself to SQL injection.

Pass in your arguments as a sequence in the second argument:

curs.execute(
    "INSERT INTO temperatur (datum, uhrzeit, ort, messwert) "
    "VALUES (CURRENT_DATE(), NOW(), %s, %s)",
    (ort, messwert))

Here (ord, messwert) is a tuple passed in as the second argument to curs.execute(). You don't need the ; in the SQL statement.

You got the error because you only passed one value to the % string format, the expression you used is "string value" % ort, as messwert was being passed in as the second argument to curs.execute(). You'd have to use "string value" % (ord, messwert) instead. However, you should avoid using string formatting altogether however, as that leaves you vulnerable to SQL injection attacks where an attacker makes use of the lack of proper escaping applied to the values interpolated into the SQL string.

Upvotes: 3

Battery_Al
Battery_Al

Reputation: 809

Everyone is right that you shouldn't use string formatting, but the quick answer for you is just that you need parentheses containing your tuple, i.e., %(ort, messwert)

Upvotes: 0

Related Questions