2

I'm getting this error in python and i don't know how to solve it. Sorry for my english, is not my native language :(

TypeError: not enough arguments for format string

save_data = "INSERT INTO mediciones_historial VALUES('%s', '%s', '%s', '%s')" % (sensor, data, data_type)

In my database I have five rows:

id (int) sensor (int) data (text) data_type(text) fecha(timestamp)

What is that I'm doing wrong?

Thanks!

0

2 Answers 2

3

In your code:

save_data = "INSERT INTO mediciones_historial VALUES('%s', '%s', '%s', '%s')" % (sensor, data, data_type)

The number of %s specifier doesn't matches number of arguments you are passing, also the column names are missing after table name

you have to make it according to the column in table but python always have a better choice.

Try using this :

save_data = "INSERT INTO mediciones_historial(column1,column2,column3) VALUES({0},{1},{2})".format(sensor, data, data_type)

but you have to take care of data type i.e if it is string or date type then use single quotes(') : '{0}' instead of {0}.

Also the above seems more understandable and readable. :)

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

3 Comments

I am glad that it helped . You may like to accept my answer also :)
This is terrible. This is vulnerable to SQL injection. execute("INSERT INTO mediciones_historial(column1,column2,column3) VALUES(%s, %s, %s)", [sensor,data,data_type])
@csharpcoder First variation of the example worked perfectly for me. I struggled to implement the second one.
3

This is because the number of values does not match the number of arguments.

save_data = "INSERT INTO mediciones_historial VALUES('%s', '%s', '%s', '%s')" % (sensor, data, data_type, fecha)

2 Comments

Thanks for the reply. Now I have this error: "Column count doesn't match value count at row 1".
Got it. Your table schema has 5 columns and we missed fecha column in insert query. Have updated my post above.

Your Answer

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.