如何在MariaDB中使用mysql-client插入引号 `'` ?

2024-05-19 18:19:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是mariaDB(15.1distrib 10.0.17-mariaDB,适用于osx10.10(x86u64))和mysqlclient==1.3.6

我只想在varcharfield中插入一个字符串。

import MySQLdb
import json

conn = MySQLdb.connect(
    host='localhost',
    port=3306,
    user='root',
    passwd='',
    db='ng')

cur = conn.cursor()

cur.execute(INSERT INTO `current_table` (`id`, `name`) VALUES (NULL, '{name}');".format(name="Lily' dog"))

conn.commit()

但我总是犯这样的错误:

^{pr2}$

如果我想通过mysql客户端插入引号该怎么办?


Tags: 字符串nameimportjsonlocalhosthostconnectconn
1条回答
网友
1楼 · 发布于 2024-05-19 18:19:26

根据Amadan的评论,在bobby-tables(防止SQL注入的站点)中,它建议:

Using the Python DB API, don't do this:

Do NOT do it this way:

cmd = "update people set name='%s' where id='%s'" % (name, id)
curs.execute(cmd)

Instead, do this:

cmd = "update people set name=%s where id=%s"
curs.execute(cmd, (name, id))

所以在我的情况下,只需将execute行修改为:

cmd = "INSERT INTO `current_table` (`id`, `name`) VALUES (NULL, %s);"
cur.execute(cmd, ("Lily's dog"))

这样可以避免引号引起的错误。在

相关问题 更多 >