0

I am trying to populate a table(whose name is parameterized). The program runs fine, up until the point where the command gets executed. Here is the code:

table_name = input("Enter table name: ")
value_name = input("Enter name: ")
sql = "INSERT INTO %s (name) VALUES (%s)" % db.escape_string(table_name), (value_name)
cursor.execute(sql)

I get the following error: TypeError: not enough arguments for format string

Thanks to anyone who takes the time to help. Have a great rest of the day :)

LittleDTLe
  • 39
  • 1
  • 6

2 Answers2

0

Just wrap the sql formatting like below and try.

sql = "INSERT INTO %s (name) VALUES (%s)" % (db.escape_string(table_name), value_name)
Praveenkumar
  • 2,056
  • 1
  • 9
  • 18
  • I tried it and I get the following error: ```AttributeError: 'MySQLConnection' object has no attribute 'escape_string' ``` – LittleDTLe May 26 '19 at 16:57
  • 1
    You may want to do escape with `connection` object. Check this https://stackoverflow.com/questions/3617052/escape-string-python-for-mysql. – Praveenkumar May 26 '19 at 16:59
0

as an alternative you good go with the new formatting format

sql = f"INSERT INTO {tab} (name) VALUES ({val})".format(tab=db.escape_string(table_name), 
                                                        val=value_name)

or

sql = f"INSERT INTO {db.escape_string(table_name)} (name) VALUES ({value_name})"
Raphael
  • 1,731
  • 2
  • 7
  • 23