Python读写数据库和乱码问题解决

来源:互联网 发布:室内定位 指纹算法 编辑:程序博客网 时间:2024/06/06 09:01

无论是Python 或者是 PHP、JAVA读写数据库错误无非三个地方的编码格式不统一。

一、语言编码

二、数据库编码

三、语言链接数据库编码

这三个地方统一编码基本就不会出现乱码问题。当然前提是你要写入的数据本身不是乱码的。

下面是Python设置数据库链接编码

conn.set_character_set('utf8')cur.execute('SET NAMES utf8;')cur.execute('SET CHARACTER SET utf8;')cur.execute('SET character_set_connection=utf8;')


下面是python写入数据库代码示例:

# SQL 插入语句        insert_color = ("INSERT INTO jy_data_wk(nianji,danyuan, keming,name,houzhui,wkURL)" "VALUES(%s,%s,%s,%s,%s,%s)")        data_color = (nianji,zjTitle,wzTitle,name,houzhui,link)        try:           # 执行sql语句           cur.execute(insert_color, data_color)                      # 提交到数据库执行           conn.commit()                   except Exception,e:           # Rollback in case there is any error           print "写入数据库错误"           print e           conn.rollback()


更新数据信息

try:                cur.execute("update jy_data set jxsjURL = '%s'  where id = '%s'" %(datas,numid))        # 提交到数据库执行        conn.commit()            except Exception,e:       # Rollback in case there is any error       print "更新数据库错误"       print e       conn.rollback()


原创粉丝点击