Search code examples
python-3.xpymysql

PyMySQL adding 100 columns dynamically


Im trying to add 100 columns at runtime using below code. i tried "https://bytes.com/topic/python/answers/45526-convert-string-tuple" but the error remains same

    import csv
    import pymysql.cursors

    connection = pymysql.connect(host='localhost',user='root',password='',db='DWM',charset='utf8mb4',cursorclass = pymysql.cursors.DictCursor)
    c = connection.cursor()

    str2 =""
    for i in range(0,100):
      str2 = "t"+str(i)
      print(str2)
      sql = "ALTER TABLE Check2 ADD column %s varchar(100)", eval(str2)
      c.execute(sql)

the error is:

   t0
   Traceback (most recent call last):
     File "check.py", line 14, in <module>
       sql = "ALTER TABLE Check2 ADD column %s varchar(100)", eval(str2)
     File "<string>", line 1, in <module>
   NameError: name 't0' is not defined

Can anyone point out my mistake? Thank you in advance for any help.


Solution

  • Try replacing

    sql = "ALTER TABLE Check2 ADD column %s varchar(100)", eval(str2)
    

    with

    sql = "ALTER TABLE Check2 ADD column {} varchar(100)".format(str2)
    

    or equivalently

    sql = f"ALTER TABLE Check2 ADD column {str2} varchar(100)"