日期:2014-05-16  浏览次数:21123 次

ubuntu下解决php和python与mysql交互时的中文乱码问题

一:首先使mysql使用utf-8字符集:

修改/etc/mysql/my.cnf
sudo gedit /etc/mysql/my.cnf

在my.cnf文件中的[client]段和 [mysqld]段加上以下两行内容:
[client]
default-character-set=utf8
[mysqld]
default-character-set=utf8

重启mysql

?

二:创建数据库时候注意

create database dbname DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

?

三:解决乱码的一个实例:

use dbname;

create table url_data(id int auto_increment primary key,
url text not null,
title text not null,
keywords text default null,
description text default null,
stress_1 text default null,
stress_2 text default null);

以下是php代码例子:

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title></title>?
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
echo "hello";
echo "hello";
$link=mysqli_connect("hostname","user","passwd") or die("error");
mysqli_select_db($link,"dbname") or die ("error");
mysqli_query($link,"SET NAMES 'UTF8'");#注意此处
$sql="select * from url_data";
$result=mysqli_query($link,$sql);
//$row=mysqli_fetch_array($result);
$row=mysqli_fetch_array($result);
$title=htmlspecialchars(stripslashes($row['title']));
$url=htmlspecialchars(stripslashes($row['url']));
echo $url;
echo $title;
echo $row['title'];
$sql="insert into url_data (url,title) values('www.baidu.com','百度')";
$result=mysqli_query($link,$sql);
echo "hello";
?>
</body>
</html>


以下是python代码例子:

?

#-*-coding:utf-8-*-
#/usr/bin/python
import MySQLdb
import sys
reload(sys)
sys.setdefaultencoding('utf8')

?

db=MySQLdb.connect(host='hostname',user='user',passwd='password',db='dbname')
cur=db.cursor()