python - 使用python pymsql在mysql查询中出错

标签 python mysql

我对这段代码中的第二个 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/

相关文章:

mysql - 如何查询非重复行但保留主键

php - 为什么 CakePHP 中的创建函数试图保存以前的条目?导致重复输入错误

python - 使用python查找我的计算机的MAC地址

python - 如何使用 any() 函数检查变量是否与列表中的任何项目匹配?

mysql - 从连接表中选择与所有选定行匹配的行

mysql - 创建 MYSQL 到 sqlite3 的 View

Python - 我如何知道何时按下表单按钮? (登出)

python - 如何在odoo中获取新记录Id?

python - 使用python在sqlite3中存储numpy数组时遇到问题

php - 在 MySQL 中添加日期周的索引