Not enough arguments for format string Python-MySQL

Question:

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!

Asked By: EEBB

||

Answers:

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)
Answered By: Samir

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. 🙂

Answered By: coder3521

a simple example. also you can manipulate it for your needs.

myDict = {'key-1': 193699, 'key-2': 206050, 'key-3': 0, 'key-N': 9999999}

values = ', '.join(f"'{str(x)}'" for x in myDict.values())

columns = ', '.join(myDict.keys())

sql = f"INSERT INTO YourTableName ({columns}) VALUES ({values});"

conn = pymysql.connect(autocommit=True, host="localhost",database='DbName', user='UserName', password='PassWord',)
with conn.cursor() as cursor:
    cursor.execute(sql)
Answered By: ali reza
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.