我正在尝试使用变量 test 作为表名将一些数据插入数据库。但不幸的是我似乎无法实现这一点。谁能帮我吗?
从我的加薪中我得到:
TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple'
我的代码:
test = "hello"
# Open database connection
db = MySQLdb.connect("127.0.0.1","admin","password","table" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = ("""INSERT INTO %s (name,
age, gender)
VALUES (%s, %s, %s)""",(test))
try:
# Execute the SQL command
cursor.execute(sql, (name, age, gender))
db.commit()
except:
raise
db.rollback()
# disconnect from server
db.close()
最佳答案
我认为 MySQLdb 不允许您使用表名称参数 - 通常这用于实际参数(有时来自用户输入并且需要清理的参数 - 名称/年龄/性别部分正确)。您可以使用 Python 的字符串格式来实现此目的:
sql = ("""INSERT INTO {table} (name, age, gender)
VALUES (%s, %s, %s)""".format(table=table), (test))
关于Python 插入 %s MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40706251/