希腊字符通过TextCtrl ERROR插入mysqldb

时间:2012-02-22 18:14:23

标签: python unicode utf-8 wxpython mysql-python

我在MySQdb中创建了一个带有名为example的表的数据库,在此表中我想保存一个名称, 这个名字是希腊语。我的问题是当我试图立即保存名称而不使用textctrl,它的确定,但是当我使用textctrl我采取错误。看看代码: 任何人都可以帮助我,请尝试使用utf-8进行编码,在utf-8中进行解码,然后进行unicode处理。

import os
import math
import random
import wx
import MySQLdb 
import sys
APP_SIZE_X = 500
APP_SIZE_Y = 300

# -*- coding: utf-8 -*-

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, size=(APP_SIZE_X, APP_SIZE_Y))

        panel = wx.Panel(self, -1,style=wx.SUNKEN_BORDER)

        wx.StaticText(panel, -1,'Name', (10, 55),style=wx.LEFT)
        self.name = wx.TextCtrl(panel, -1, '', (110, 55), (120, -1))

        save = wx.Button(panel, 1, 'Save', (70, 215),(130,-1))
        save.Bind(wx.EVT_BUTTON,self.OnSaveAsFile)

        quitbtn = wx.Button(panel, 1, 'Quit', (250, 215),(130,-1))
        quitbtn.Bind(wx.EVT_BUTTON,self.OnQuit)

    def OnSaveAsFile(self, event):

        idis="000"
        newname=self.name.GetValue()



        db=MySQLdb.connect(host="localhost",use_unicode="True",charset="utf8",user="root",passwd="root",db="test")
        cursor=db.cursor()

        sql="""INSERT INTO TB_EXAMPLE(name) VALUES("%s","%s")"""%(idis,newname)


        try:


            cursor.execute(sql)

            db.commit()
            print 'save ok'
        except:

            print 'no save'
            db.rollback()

    def OnQuit(self,e):

        self.Close()








class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'form1.py')
        frame.Show(True)
        self.SetTopWindow(frame)
        return True

app = MyApp(0)
app.MainLoop()

2 个答案:

答案 0 :(得分:1)

您使用的是unicode版本的wxPython吗?这可能只是解决了这个问题。或者您可以查看以下两个链接:

你可以通过做这样的事情来伪造它:

newname= u"%s" % self.name.GetValue()

答案 1 :(得分:0)

如果让db模块执行参数替换而不是Python执行它会有什么不同吗? (如果您要插入用户输入的值,这样更安全。)例如:

cursor.execute("INSERT INTO TB_EXAMPLE(name) VALUES(%s,%s)", (idis,newname))

通过阅读MySQLdb文档,当设置charset连接参数时,它听起来也会自动转换为unicode。

相关问题