本文主要讲解如何使用 PyQt4 实现一个自定义的不规则窗体。

custom widget

源码

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
class Widget(QWidget):
def __init__(self, parent = None):
super(Widget, self).__init__(parent)
self.setWindowFlags(Qt.ToolTip)
self.setAttribute(Qt.WA_TranslucentBackground)
self.setMouseTracking(True)
self.startPos = QPoint(0,0)
self.dragPosition = QPoint(0, 0)
self.resize(QApplication.desktop().size())
quit = QAction(self.tr(""), self)
quit.setShortcut(self.tr("Ctrl+Q"))
self.connect(quit, SIGNAL("triggered()"), qApp.quit)
self.addAction(quit)
self.setContextMenuPolicy(Qt.ActionsContextMenu)
def paintEvent(self, event):
painter = QPainter(self)
painter.setPen(QColor(255,0,0))
painter.setBrush(QColor(255,0,0))
self.drawPainter(painter, QColor(255, 0, 0))
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.dragPosition = event.globalPos() - self.frameGeometry().topLeft()
event.accept()
def mouseMoveEvent(self, event):
if event.buttons() & Qt.LeftButton:
self.startPos += (event.pos() - self.dragPosition)
self.dragPosition = event.pos()
self.move(event.globalPos() - self.dragPosition)
if self.size().width() < QApplication.desktop().width():
self.resize(self.size() + QSize(1, 1))
else:
self.resize(self.size() - QSize(1, 1))
event.accept()
def resizeEvent(self, event):
bmp = QBitmap(self.size())
bmp.fill(QColor(255,255,255))
painter = QPainter(bmp)
painter.setPen(QColor(0,0,0))
painter.setBrush(QColor(0,0,0))
self.drawPainter(painter, QColor(0, 0, 0))
self.setMask(bmp)
def drawPainter(self, painter, color):
path = QPainterPath()
path.addEllipse(self.startPos.x(), self.startPos.y(), 100, 100)
painter.fillPath(path, color)
painter.end()
if __name__ == "__main__":
app = QApplication(sys.argv)
widget = Widget()
widget.show()
sys.exit(app.exec_())

解析

定义窗体

首先定义一个 Widget,并继承 QWidget,在构造函数 __init__ 中调用基类 QWidget 的构造函数 super(Widget, self).__init__(parent)。

1
2
3
class Widget(QWidget):
def __init__(self, parent = None):
super(Widget, self).__init__(parent)

并设置窗体属性:

1
2
3
4
5
6
7
8
9
10
11
12
13
# 设置窗体置顶显示
self.setWindowFlags(Qt.ToolTip)
# 设置窗体背景透明
self.setAttribute(Qt.WA_TranslucentBackground)
self.setMouseTracking(True)
# 初始化成员变量
self.startPos = QPoint(0,0)
self.dragPosition = QPoint(0, 0)
# 设置窗体大小
self.resize(QApplication.desktop().size())

创建右键菜单

创建右键菜单,并连接相应的槽。

1
2
3
4
5
6
7
8
9
10
11
12
# 创建quit菜单项
quit = QAction(self.tr(""), self)
quit.setShortcut(self.tr("Ctrl+Q"))
# 连接qApp.quit槽函数
self.connect(quit, SIGNAL("triggered()"), qApp.quit)
# 将菜单项添加至窗体上
self.addAction(quit)
# 设置上下文菜单
self.setContextMenuPolicy(Qt.ActionsContextMenu)

paintEvent 函数

创建一个不规则的窗体,需要重写 QWidget 类的 paintEvent 函数:

1
2
3
4
5
def paintEvent(self, event):
painter = QPainter(self)
painter.setPen(QColor(255,0,0)) # 设置画笔颜色
painter.setBrush(QColor(255,0,0)) # 设置画刷颜色
self.drawPainter(painter, QColor(255, 0, 0)) # 不规则窗体绘制

mousePressEvent 函数

由于隐藏了不规则窗体的边框,想拖动它,还需实现 mousePressEvent 和 mouseMoveEvent 函数:

1
2
3
4
5
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.dragPosition = event.globalPos() - self.frameGeometry().topLeft()
event.accept()

mouseMoveEvent 函数

1
2
3
4
5
6
7
8
9
10
11
12
13
def mouseMoveEvent(self, event):
if event.buttons() & Qt.LeftButton:
self.startPos += (event.pos() - self.dragPosition)
self.dragPosition = event.pos()
self.move(event.globalPos() - self.dragPosition)
# 用来解决窗体无法拖动的现象
if self.size().width() < QApplication.desktop().width():
self.resize(self.size() + QSize(1, 1))
else:
self.resize(self.size() - QSize(1, 1))
event.accept()

窗体掩膜

1
2
3
4
5
6
7
8
9
10
def resizeEvent(self, event):
bmp = QBitmap(self.size())
bmp.fill(QColor(255,255,255))
painter = QPainter(bmp)
painter.setPen(QColor(0,0,0))
painter.setBrush(QColor(0,0,0))
self.drawPainter(painter, QColor(0, 0, 0))
self.setMask(bmp) # 设置窗体掩膜

绘制不规则窗体

1
2
3
4
5
6
def drawPainter(self, painter, color):
path = QPainterPath()
# 绘制圆形窗体
path.addEllipse(self.startPos.x(), self.startPos.y(), 100, 100)
painter.fillPath(path, color)
painter.end() # 解决运行时的段错误

若无 painter.end() 一行代码,运行时将产生段错误:

QPaintDevice: Cannot destroy paint device that is being painted
QPaintDevice: Cannot destroy paint device that is being painted
段错误

注: 用鼠标拖动圆形窗体时,窗体移动较缓慢,下次再分析其原因。

本文主要讲解如何使用 PyQt4 实现一个托盘程序(本程序改写自 Qt4 系统托盘程序)。

源码

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/python
# -*- coding: utf-8 -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
class Widget(QWidget):
def __init__(self, parent = None):
super(Widget, self).__init__(parent)
self.setWindowTitle(self.tr("Tray"))
self.setWindowIcon(QIcon("./img/tray.png"))
trayIcon = QSystemTrayIcon(QIcon("./img/tray.png"), self)
trayIcon.setToolTip(self.tr("this is a pyqt tray test"))
trayIcon.setContextMenu(self.CreateTrayMenu())
trayIcon.setVisible(True)
def CreateTrayMenu(self):
menu = QMenu(self.tr("menu"), self)
minAction = QAction(self.tr("MinSize"), self)
self.connect(minAction, SIGNAL("triggered()"), self.showMinimized)
maxAction = QAction(self.tr("Maxsize"), self)
self.connect(maxAction, SIGNAL("triggered()"), self.showMaximized)
restoreAction = QAction(self.tr("Restore"), self)
self.connect(restoreAction, SIGNAL("triggered()"), self.showNormal)
quitAction = QAction(self.tr("Quit"), self)
self.connect(quitAction, SIGNAL("triggered()"), qApp.quit)
menu.addAction(minAction)
menu.addAction(maxAction)
menu.addAction(restoreAction)
menu.addSeparator()
menu.addAction(quitAction)
return menu
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setQuitOnLastWindowClosed(False)
win = Widget()
win.show()
sys.exit(app.exec_())

解析

定义窗体

首先定义一个 Widget,并继承 QWidget,在构造函数 __init__ 中调用基类 QWidget 的构造函数 super(Widget, self).__init__(parent)。

1
2
3
class Widget(QWidget):
def __init__(self, parent = None):
super(Widget, self).__init__(parent)

并设置窗体标题和窗体图标:

1
2
self.setWindowTitle(self.tr("Tray"))
self.setWindowIcon(QIcon("./img/tray.png"))

创建托盘

创建托盘,并设置工具提示信息,上下文菜单和窗体可视化等属性。

1
2
3
4
5
trayIcon = QSystemTrayIcon(QIcon("./img/tray.png"), self)
trayIcon.setToolTip(self.tr("this is a pyqt tray test"))
trayIcon.setContextMenu(self.CreateTrayMenu())
trayIcon.setVisible(True)

创建托盘菜单并连接相应的响应函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def CreateTrayMenu(self):
# 创建菜单
menu = QMenu(self.tr("menu"), self)
# 窗体最小化
minAction = QAction(self.tr("MinSize"), self)
self.connect(minAction, SIGNAL("triggered()"), self.showMinimized)
# 窗体最大化
maxAction = QAction(self.tr("Maxsize"), self)
self.connect(maxAction, SIGNAL("triggered()"), self.showMaximized)
# 还原
restoreAction = QAction(self.tr("Restore"), self)
self.connect(restoreAction, SIGNAL("triggered()"), self.showNormal)
# 退出
quitAction = QAction(self.tr("Quit"), self)
self.connect(quitAction, SIGNAL("triggered()"), qApp.quit)
# 添加菜单项
menu.addAction(minAction)
menu.addAction(maxAction)
menu.addAction(restoreAction)
menu.addSeparator()
menu.addAction(quitAction)
return menu

前言

PyQt4 开发环境的安装,请参考PyQt4 国际化与本地化一文。

本篇主要讲解在 QGraphicsView Framework 中增加右键菜单,关于QGraphicsView,后续帖子将重点讲述。

源码

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/python
#
# -*- coding: utf-8 -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
scene = QGraphicsScene()
view = QGraphicsView()
view.setScene(scene)
view.setSceneRect(0, 0, 1280, 1024)
view.centerOn(0, 0)
view.setRenderHint(QPainter.Antialiasing)
item = QGraphicsLineItem()
item.setLine(50, 50, 400, 400)
scene.addItem(item)
view.setContextMenuPolicy(Qt.CustomContextMenu)
self.setCentralWidget(view)
view.customContextMenuRequested.connect(self.showContextMenu)
self.setWindowTitle(self.tr("GraphicsView PyQT4"))
def showContextMenu(self, pos):
contextMenu = QMenu("viewMenu", self.view)
action1 = QAction(self.tr("item A"), self)
contextMenu.addAction(action1)
action2 = QAction(self.tr("item B"), self)
contextMenu.addAction(action2)
contextMenu.exec_(QCursor.pos())
if __name__ == "__main__":
app = QApplication(sys.argv)
mainw = MainWindow()
mainw.show()
sys.exit(app.exec_())

解析

主窗体

1
2
3
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)

定义一个主窗体MainWindow,继承QMainWindow。其中 __init__ 方法,相当于 C++ 中的构造函数。而 super(MainWindow, self).__init__(parent) 方法则是调用其父类的构造函数,从而模拟 C++ 继承特性。

QGraphicsView 框架

1
2
3
4
scene = QGraphicsScene()
view = QGraphicsView()
view.setScene(scene)
view.setSceneRect(0, 0, 1280, 1024)

QGraphicsScene() 用来生成一个场景实例,QGraphicsView() 用来生成一个视图实例。setScene() 用来设置场景,setSceneRect() 用来设置场景大小。

1
2
view.centerOn(0, 0)
view.setRenderHint(QPainter.Antialiasing)

centerOn() 用来设置水平滚动条和垂直滚动条的初始位置分别为最左端和最上端。setRenderHint(QPainter.Antialiasing) 用来处理反锯齿效果。

右键菜单

1
2
3
4
view.setContextMenuPolicy(Qt.CustomContextMenu)
...
view.customContextMenuRequested.connect(self.showContextMenu)

上面两行代码用来绑定 GraphicsView 右键菜单。

显示右键菜单:

1
2
3
4
5
6
7
def showContextMenu(self, pos):
contextMenu = QMenu("viewMenu", self.view)
action1 = QAction(self.tr("item A"), self)
contextMenu.addAction(action1)
action2 = QAction(self.tr("item B"), self)
contextMenu.addAction(action2)
contextMenu.exec_(QCursor.pos())

在右键菜单中增加两个菜单项,并添加到右键菜单中。当在 QGraphicsView 视图区域点击右键时,将会弹出右键菜单。

心学四诀

无善无恶心之体,
有善有恶意之动。
知善知恶是良知,
为善去恶是格物。

人性本无善恶之分。但随着年龄增长,社会阅历的增加,受欲望的左右,才有了善恶之分。能区分善恶,并做取舍,就是有良知的人。能趋善除恶,就是圣人之道。

安装PyQt4

首先安装 PyQt4 开发环境,使用以下命令进行安装:

1
$ sudo apt-get install python-qt4 python-qt4-dev pyqt4-dev-tools

注:笔者的机器安装的是 Ubuntu 12.04。

PyQt4 示例

安装完毕后,按照惯例,编写一个 mainwindow.py 验证下,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
class MainWindow(QMainWindow):
def __init__(self, app, parent=None):
super(MainWindow, self).__init__(parent)
label = QLabel("Hello PyQt4!")
self.setCentralWidget(label)
self.setWindowTitle("PyQt4 main Window")
if __name__ == "__main__":
app = QApplication(sys.argv)
win = MainWindow(app)
win.show()
sys.exit(app.exec_())

国际化与本地化

处理字符串

将程序中所有需要做国际化与本地化处理的字符串用self.tr()方法处理。

1
2
3
label = QLabel(self.tr("Hello PyQt4!"))
...
self.setWindowTitle(self.tr("PyQt4 main Window"))

添加代码

待字符串处理完后,还需在 QApplication 后面添加以下代码:

1
2
3
translator = QTranslator()
translator.load("zh_CN.qm")
app.installTranslator(translator)

生成 .ts 文件

在终端中,使用 pylupdate4 命令生成 .ts 文件,操作如下:

1
$ pylupdate4 mainwindow.py -ts zh_CN.ts

zh_CN.ts 的内容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="zh_CN">
<context>
<name>MainWindow</name>
<message>
<location filename="mainwindow.py" line="13"/>
<source>Hello PyQt4!</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="mainwindow.py" line="15"/>
<source>PyQt4 main Window</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>

翻译

使用编辑器打开 zh_CN.ts,并修改内容并保存:

1
2
3
4
5
6
7
8
9
10
11
<name>MainWindow</name>
<message>
<location filename="mainwindow.py" line="13"/>
<source>Hello PyQt4!</source>
<translation type="unfinished">你好,PyQt4!</translation>
</message>
<message>
<location filename="mainwindow.py" line="15"/>
<source>PyQt4 main Window</source>
<translation type="unfinished">PyQt4 主窗体</translation>
</message>

生成 .qm

使用 lrelease 工具生成 zh_CN.qm 文件,如下:

1
$ lrelease zh_CN.ts

运行

在终端中运行 mainwindow.py,如下:

1
$ python mainwindow.py

看到了什么?界面上出现了中文,说明本地化处理OK!

Clang 简介

Clang (发音为 /ˈklæŋ/ 类似英文单字 clang) 是一个 C、C++ 和 Objective-C 编程语言的编译器前端。它采用了底层虚拟机(LLVM)作为其后端。它的目标是提供一个GNU编译器套装(GCC)的替代品。作者是克里斯·拉特纳,在苹果公司的赞助支持下进行开发,而源代码授权是使用类 BSD 的开源授权。

Clang 专案包括 Clang 前端和 Clang 静态分析器等。(摘自维基)

安装

在 Ubuntu 12.04 上安装 Clang 和 llvms:

::sh
$ sudo apt-get install clang llvm-3.0

使用 Clang 编译 QT4

1、首先编辑一个 hello.cpp,其内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <QApplication>
#include <QLabel>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QLabel *label = new QLabel;
label->setText("<center><h1><font color=blue>Hello World!</font></h1></center>");
label->setWindowTitle("QT");
label->resize(200, 50);
label->show();
return app.exec();
}

2、生成.pro

打开终端,进入到 hello.cpp 所在目录,运行以下命令:

1
$ qmake -project

3、编辑.pro

编辑hello.pro文件,并在文件末尾增加以下内容:

TARGET_EXT = .bc
QMAKE_EXT_OBJ = .bc
QMAKE_CXXFLAGS += -emit-llvm
QMAKE_CXX = clang++
QMAKE_CC = clang
QMAKE_LINK = $(CXX)
QMAKE_RUN_CXX = $(CXX) $(CXXFLAGS) $(INCPATH) -c $(SOURCES) -o $obj
QMAKE_RUN_CC = $(CC) $(CCFLAGS) $(INCPATH) -c $(SOURCES) -o $obj

4、编译

1
2
$ qmake
$ make

5、运行
运行程序,屏幕上将出现 QT 程序:

1
$ ./hello

参考资料

准备工作

1、安装MYSQL

1
$ sudo apt-get install mysql-server mysql-workbench

2、安装MYSQL C开发包

1
$ sudo apt-get install libmysqlclient-dev

注:安装MySQL需要设置管理员root帐号密码(非Linux账户root密码)。

建立数据表

MySQL安装完毕后,使用以下命令操作:

1
$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g. 
Your MySQL connection id is 36 
Server version: 5.5.24-0ubuntu0.12.04.1 (Ubuntu) 

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. 

Oracle is a registered trademark of Oracle Corporation and/or its 
affiliates. Other names may be trademarks of their respective 
owners. 

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. 

mysql>

1、添加一般用户

mysql> CREATE USER young@localhost IDENTIFIED BY 'young'; 
Query OK, 0 rows affected (0.02 sec) 

mysql> GRANT ALL ON *.* to young@localhost; 
Query OK, 0 rows affected (0.00 sec) 

mysql>

2、使用一般用户登录

1
$ mysql -u young -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g. 
Your MySQL connection id is 39 
Server version: 5.5.24-0ubuntu0.12.04.1 (Ubuntu) 

Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. 

Oracle is a registered trademark of Oracle Corporation and/or its 
affiliates. Other names may be trademarks of their respective 
owners. 

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. 

mysql>

3、建立数据库

mysql> CREATE DATABASE testdb; 
Query OK, 1 row affected (0.00 sec)

察看数据库

mysql> show databases; 

+--------------------+ 
| Database           | 
+--------------------+ 
| information_schema | 
| mysql              | 
| performance_schema | 
| test               | 
| testdb             | 
+--------------------+ 
5 rows in set (0.01 sec)

4、建立数据表

mysql> use testdb; 
Database changed 

mysql> CREATE TABLE student(stuid CHAR(11), name VARCHAR(20), sex CHAR(1), birth DATE, major VARCHAR(30), PRIMARY KEY(stuid)); 
Query OK, 0 rows affected (0.33 sec)

5、导入数据

编写一个student.txt的文件,文件使用TAB分隔,内容如下:

20111110001     Jason   m       1987-01-01      ComputerScience
20111110002     Peter   m       1989-10-23      Mathematics
20111110003     Marry   f       1989-11-11      Art

注:需将student.txt文件放置在/var/lib/mysql目录下,否则导入数据时无法找到文件。

将数据导入testdb数据库:

mysql> load data INFILE './student.txt' into table student; 
Query OK, 3 rows affected (0.18 sec) 
Records: 3  Deleted: 0  Skipped: 0  Warnings: 0 

mysql> use testdb; 
Database changed 
mysql> select * from student;

+-------------+-------+------+------------+-----------------+ 
| stuid       | name  | sex  | birth      | major           | 
+-------------+-------+------+------------+-----------------+ 
| 20111110001 | Jason | m    | 1987-01-01 | ComputerScience | 
| 20111110002 | Peter | m    | 1989-10-23 | Mathematics     | 
| 20111110003 | Marry | f    | 1989-11-01 | Art             | 
+-------------+-------+------+------------+-----------------+ 
3 rows in set (0.00 sec)

测试连接Mysql

编辑一个db-demo.c程序(来源自mysqlcapitutorial):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <stdio.h>
#include <stdlib.h>
#include <mysql/mysql.h>
#define USER "young" // mysql user name
#define PASSWD "young" // mysql password
int main(int argc, char **argv)
{
MYSQL *conn;
MYSQL_RES *result;
MYSQL_ROW row;
int num_fields;
int i;
// initilize mysql
conn = mysql_init(NULL);
if (conn == NULL)
{
printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
exit(1);
}
// connect the database testdb
if (mysql_real_connect(conn, "localhost", USER,
PASSWD, "testdb", 0, NULL, 0) == NULL)
{
printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
exit(1);
}
// query with SQL
if (mysql_query(conn, "select * from student"))
{
printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
exit(1);
}
// store the query result
result = mysql_store_result(conn);
num_fields = mysql_num_fields(result);
// show the result
while ((row = mysql_fetch_row(result)))
{
for (i = 0; i &lt; num_fields; i++)
{
printf("%s ", row[i] ? row[i] : "NULL");
}
printf("\n");
}
mysql_free_result(result);
// close the database testdb
mysql_close(conn);
return 0;
}

使用以下命令编译:

1
$ gcc db-demo.c -lmysqlclient -o db-demo

运行:

1
$ ./db-demo
20111110001 Jason m 1987-01-01 ComputerScience 
20111110002 Peter m 1989-10-23 Mathematics 
20111110003 Marry f 1989-11-01 Art

数据库导出:

1
$ mysqldump -u user -p database > db.sql

eg:

1
$ mysqldump -u young -p testdb > /home/mutse/testdb.sql

数据表导出:

1
$ mysqldump -u user -p database table > table.sql

eg:

1
$ mysqldump -u young -p testdb student > /home/mutse/student.sql
参考资料:

最近一段时间学习 Building Blog with Django,却一直没解决 MySql 中文编码问题。然而,昨晚折腾了几个小时,问题得以解决,遂记之。

设置中文编码

编辑 /etc/mysql/my.cnf

1
2
$ sudo cp /etc/mysql/my.cnf /etc/mysql/my.cnf_20120905
$ sudo vim /etc/mysql/my.cnf

添加的内容如下:

[client] 
default-character-set=utf8 

[mysqld] 
# 
# * Basic Settings 
# 
default-storage-engine=INNODB 
lower_case_table_names=1 
character_set_server=utf8 
collation-server=utf8_general_ci 

[mysql] 
#no-auto-rehash  # faster start of mysql but no tab completition 
default_character_set=utf8 

重启Mysql服务

1
$ sudo service mysql restart

查看编码

终端登录mysql,并输入:

mysql>show variables like 'character%';
参考资料: