如何使用 mysql-client 将引号 `'` 插入到 mariaDB 中?
How to intsert quotation mark `'` into mariaDB using mysql-client?
我正在使用 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注射的网站)中,建议:
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"))
这样可以避免引号导致的错误。
我正在使用 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注射的网站)中,建议:
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"))
这样可以避免引号导致的错误。