Python插入SQL unicode错误

时间:2015-01-22 22:10:40

标签: python mysql unicode

我有以下错误:

    db = MySQLdb.connect(host="localhost", # host
                 user="root", # username
                  passwd="", # password
                  db="test",charset='utf8') #

    cur = db.cursor() 
    x = "испытание" # random unicode characters
    sql = "INSERT INTO links(test) VALUES(N'%s');"
    lst = ( x ) #x is unicode data
    cur.execute(sql,lst)

我得到的错误是:MySQL错误[1064]:您的SQL语法中有错误;检查与MySQL服务器版本对应的手册,以获得正确的语法...

2 个答案:

答案 0 :(得分:1)

x = "испытание" # random unicode characters

(你使用的是什么Python版本?如果2.x,那些不是Unicode字符,它们就是字节。)

sql = "INSERT INTO links(test) VALUES(N'%s');"

使用参数化查询时,不要包含字符串文字分隔符''。对于参数标记为%s的MySQLdb,它应该只是:

sql = "INSERT INTO links(test) VALUES(%s);"

(注意在MySQL中也不需要NVARCHAR。)

lst = ( x ) #x is unicode data

此处lstx的值相同,您还没有得到元组。如果你真的想要一个元组,那么说(x,),但可能使用实际列表[x]更清楚。

答案 1 :(得分:0)

您想要插入什么价值?没有。 N'%s'代表。我猜你试图从一个表单插入,所以我已经在这个代码上工作,测试它并正在运行。 首先使用2列employee_id和lastname创建数据库。然后测试这段代码。它会对你有用。如果你做得对,请将其作为答案。 Sectona ...

#!c:/python25/python

import MySQLdb

# Import modules for CGI handling 
import cgi, cgitb 

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# get form data from form field

employee_id = form.getvalue('employee_id')
lastname  = form.getvalue('lastname')



# Open database connection
db = MySQLdb.connect("localhost","sectona","sectona90","sectona_db" )

# prepare a cursor object using cursor() method
cursor = db.cursor()


sql = "INSERT INTO EMPLOYEE(employee_id, \
       lastname) \
       VALUES ('%s', '%s')" % \
       (employee_id, lastname)

try:
   # Execute the SQL command
   cursor.execute(sql)
   # Commit your changes in the database
   db.commit()
except:
   # Rollback in case there is any error
   db.rollback()

# disconnect from server
db.close()
print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<body>'
print '<h2>Data Submitted Successfully</h2>'
print "<b>Employee Identity:</b> %s<br>" % (employee_id)
print "<b>Last Name:</b> %s<br>" % (lastname)

print '</body>'
print '</html>'