• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

mysql 搞代码 7年前 (2018-06-05) 164次浏览 已收录 0个评论

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”&gt;
<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()
cur.execute(“set NAMES UTF8”)
cur.execute(“select * from url_data”)
r=cur.fetchall()
print r[0][2]
print r[1][2]
print r[0][2].decode(‘utf8’)

 

cur.execute(“insert into url_data (url,title) values(‘www.baidu.com’,’哈哈’)”)
db.commit()
cur.close()
db.close()
print “hello”



搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:ubuntu上解决php和python与mysql交互时的中文乱码有关问题

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址