gpt4 book ai didi

python - 如何使用 mysql-client 将引号 `' ` 插入到 mariaDB 中?

转载 作者:行者123 更新时间:2023-11-28 23:51:57 41 4
gpt4 key购买 nike

我正在使用 mariaDB(版本 15.1 Distrib 10.0.17-MariaDB,适用于 osx10.10 (x86_64))和 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()

但我总是得到这样的错误:

_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 's dog', NULL)' at line 1")

mysql-client要插入引号怎么办?

最佳答案

根据 Amadan 的评论,在 bobby-tables (防止SQL注入(inject)的站点),提示:

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))

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

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

这样可以避免引号导致的错误。

关于python - 如何使用 mysql-client 将引号 `' ` 插入到 mariaDB 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32470451/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com