the code is like below:
代码如下:
Connect server
连接服务器
MySQLdb.connect(host=ip, user='root', passwd='root',db='test',use_unicode=True,charset="utf8")
......
sql = "INSERT INTO ci(id,name) VALUES (493,u'Hello')"
print sql
ret = root.execute(sql)
.....
In the server, the tyoe of name is VARCHAR(1000). Then when i run this script, it shows error 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
在服务器中,名字的tyoe是VARCHAR(1000)。然后当我运行这个脚本时,它会显示错误编程错误:(1064,“SQL语法中有错误;检查与MySQL服务器版本相对应的手册,以获得使用near的正确语法
But when i replace u'Hello' with 'Hello', it is OK. So maybe it doesn't support unicode,then i insert unicode string such as "你好" to the table by GUI manually, it is also OK. I can not find what is the reason, who can help me
但是当我用Hello代替u'Hello时,没有问题。也许它不支持unicode,然后插入unicode字符串,如“你”好手动的GUI,也是好的。我找不到原因,谁来帮助我
1 个解决方案
#1
3
MySQL needs strings to be enclosed in straight quotes: '你好', 'u' symbol is not allowed. Just declare the whole string as Unicode and pass it to MySQL. Here I am using a prepared statement:
MySQL需要字符串直接包含在引号:“你好”,“u”符号是不允许的。只要将整个字符串声明为Unicode并将其传递给MySQL即可。我在这里用的是事先准备好的声明:
sql = u"INSERT INTO ci(id,name) VALUES (493,'你好')"
Don't forget to run "SET NAMES 'UTF-8'" (or UTF-16 - don't know, what encoding you are using) after you connect to MySQL to ensure, that the server will correctly interpret the string you send it.
在连接到MySQL之后,不要忘记运行“设置名称‘UTF-8’”(或者UTF-16——不知道您正在使用什么编码),以确保服务器将正确地解释您发送的字符串。
#1
3
MySQL needs strings to be enclosed in straight quotes: '你好', 'u' symbol is not allowed. Just declare the whole string as Unicode and pass it to MySQL. Here I am using a prepared statement:
MySQL需要字符串直接包含在引号:“你好”,“u”符号是不允许的。只要将整个字符串声明为Unicode并将其传递给MySQL即可。我在这里用的是事先准备好的声明:
sql = u"INSERT INTO ci(id,name) VALUES (493,'你好')"
Don't forget to run "SET NAMES 'UTF-8'" (or UTF-16 - don't know, what encoding you are using) after you connect to MySQL to ensure, that the server will correctly interpret the string you send it.
在连接到MySQL之后,不要忘记运行“设置名称‘UTF-8’”(或者UTF-16——不知道您正在使用什么编码),以确保服务器将正确地解释您发送的字符串。