2015-09-09 22 views
1

我正在使用mariaDB(Ver 15.1 Distrib 10.0.17-MariaDB,用于osx10.10(x86_64))和mysqlclient==1.3.6如何使用mysql-client将引号```插入到mariaDB中?

我只想插入一个字符串到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客户端插入引号?

+2

'conn.escape_string(“Lily'dog”)''。总是逃避你的弦乐。必须[Bobby Tables](http://bobby-tables.com)链接。 – Amadan

+0

@Amadan使用'conn.escape_string(“Lily'dog”)'后,仍然存在错误:'_mysql_exceptions.ProgrammingError:(1064,'您的SQL语法错误;检查与您的MariaDB服务器相对应的手册版本的正确语法使用附近的狗'\',空)\'在1')' – Sinux

+0

请显示你如何使用它(通过编辑帖子和追加新命令)。 – Amadan

回答

1

根据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")) 

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