PyMySQL动态添加100列

时间:2017-02-17 16:28:25

标签: python-3.x pymysql

我尝试使用下面的代码在运行时添加100列。 我试过" https://bytes.com/topic/python/answers/45526-convert-string-tuple" 但错误仍然相同

    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)

错误是:

   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

有谁可以指出我的错误? 提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

尝试替换

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

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

或等效

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