Python MySQLdb 使用utf-8 编码插入中文数据

用Python的MySQLdb插入UTF-8编码的内容时经常会出问题,主要是Mysql数据库编码和python程序文档编码两个方面。本文旨在提供一个例子来解决Python插入UTF8中文数据的问题

使用环境:
Python 2.5 for Windows
MySQLdb 1.2.2 for Python 2.5
MySQL 4.1.22

源代码如下:

#!/usr/bin/env python
#coding=utf-8

import MySQLdb

#DB parameter
strHost = '192.168.6.184'
strDB = 'test'
strUser = 'root'
strPasswd = 'admin1111'

#connect to DB
conn = MySQLdb.connect(host=strHost, db=strDB, user=strUser, passwd=strPasswd, charset="utf8")
curs = conn.cursor()

curs.execute("SET NAMES utf8")
curs.execute("SET CHARACTER_SET_CLIENT=utf8")
curs.execute("SET CHARACTER_SET_RESULTS=utf8")
conn.commit()

strVal = "广州"
strSql = "INSERT INTO t1( val ) values( '%s' )" % strVal
ret = curs.execute(strSql)
conn.commit()


curs.close()
conn.close()

转自:http://hi.baidu.com/onekunp/item/80771e3fd63905be124b1440

posted @ 2013-07-26 09:30  simon1024  阅读(837)  评论(0)    收藏  举报