我尝试使用下面的代码在运行时添加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
有谁可以指出我的错误? 提前感谢您的帮助。
答案 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)"