我对这段代码中的第二个 sql 有一个 sql 查询错误:我知道转义单引号是有问题的,但我不知道如何在我的参数中转义。这是我的第一个问题
我的第二个问题是关于另一种引用:`,我不知道为什么我需要它围绕 y 字段和表名,而我在 SO 上看到所有 sql 查询都不需要它。有关信息,我使用 easydevserver 在本地主机上使用 mysql 服务器。
提前感谢您的提示!
db = Database()
ea = Ean()
sql = 'SELECT * FROM `table 2` WHERE `categorie` = "Lego"'
listeproduit = db.select(sql)
for record in listeproduit:
skuref = "Mg "+ record[0][0:20]
print (skuref)
ean = ea.generateEAN13CheckDigit()
lastpost = record[0]
lastean = ean
print(lastpost)
print (lastean
sql = """UPDATE `table 2` SET `ean`='%s' WHERE `nom`='%s'"""%(lastean,lastpost)
print (sql)
db.insert(sql)
这是我启动时的输出:
Lego Lego 79116 Tortues Ninja : L'évasion en camion
3700775101267
UPDATE `table 2` SET `ean`='3700775101267' WHERE `nom`='Lego Lego 79116 Tortues Ninja : L'évasion en camion'
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'évasion en camion'' at line 1")
如果您需要我的更多代码,我会使用这样的类数据库:
class Database(object):
def __init__(self):
self.db = pymysql.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="", # your password
db="mgdeal", # name of the data base
charset='utf8',
use_unicode=True,
init_command='SET NAMES UTF8')
def insert (self, sql):
cursor= self.db.cursor()
cursor.execute(sql)
newID = cursor.lastrowid
self.db.commit()
cursor.close()
return newID
最佳答案
你可以用这样的方式转义引号:str(lastpost).replace("'","\\'")
它会告诉 mysql 引用是文本的一部分。
关于python - 使用python pymsql在mysql查询中出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35360816/