PyMySQL 动态添加 100 列
PyMySQL adding 100 columns dynamically
我正在尝试使用以下代码在运行时添加 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
谁能指出我的错误?
预先感谢您的帮助。
尝试更换
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)"
我正在尝试使用以下代码在运行时添加 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
谁能指出我的错误? 预先感谢您的帮助。
尝试更换
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)"