我在这个问题上遇到了很多麻烦,并且一直在检查堆栈溢出和网络上的答案。我试图替换此语句中的变量(“DELETE FROM USERNAME =”+ [variable])
这是我的代码:
import mysql.connector as mysql
global usr_to_rmv
usr_to_rmv = 'Hoyt'
global from_table
from_table = "accounts"
global from_db
from_db = "users"
global from_column
from_column = "username"
cnx = mysql.connect(user = 'root', password = 'mag1c1234',
host = 'localhost',
database = from_db)
cursor = cnx.cursor()
# Uncomment to reset new data to 1
cursor.execute("ALTER TABLE accounts AUTO_INCREMENT = 1")
removeuser = ("DELETE FROM" + " " + from_table + " " + "WHERE" + " " + from_column + "=" + usr_to_rmv);
cursor.execute(removeuser)
query_1 = ("SELECT * FROM accounts");
cursor.execute(query_1)
for row in cursor.fetchall():
print(row)
cnx.commit()
cursor.close()
cnx.close()
所有帮助表示赞赏。谢谢:))
编辑:这是我遇到的错误mysql.connector.errors.ProgrammingError:1054(42S22):'where子句'中的未知列'Hoyt'
答案 0 :(得分:0)
您通常不希望通过连接类似的变量来构建您的sql语句,而是使用参数化语句。 %s
是占位符,您需要可变数据(作为第二个参数传递给execute
:
sql_delete = "DELETE FROM accounts WHERE username = %s"
sql_data = (usr_to_remove,)
cursor.execute(sql_delete, sql_data)
如果您绝对必须使用表和列名称的可变数据,您可以(只是完全确定您确切知道该数据是什么),但继续传递必须作为参数转义的数据:
sql_delete = "DELETE FROM " + from_table + " WHERE " + from_column + " = %s"
sql_data = (usr_to_remove,)
cursor.execute(sql_delete, sql_data)
查看更多示例here。此外,如果走第二条路线,请确保您了解potential downsides。