This man is too old to remember everything in his brain. Right now, he needs a place to write down what he has studied.
標籤
4GL
(1)
人才發展
(10)
人物
(3)
太陽能
(4)
心理
(3)
心靈
(10)
文學
(31)
生活常識
(14)
光學
(1)
名句
(10)
即時通訊軟體
(2)
奇狐
(2)
爬蟲
(1)
音樂
(2)
產業
(5)
郭語錄
(3)
無聊
(3)
統計
(4)
新聞
(1)
經濟學
(1)
經營管理
(42)
解析度
(1)
遊戲
(5)
電學
(1)
網管
(10)
廣告
(1)
數學
(1)
機率
(1)
雜趣
(1)
證券
(4)
證券期貨
(1)
ABAP
(15)
AD
(1)
agentflow
(4)
AJAX
(1)
Android
(1)
AnyChart
(1)
Apache
(14)
BASIS
(4)
BDL
(1)
C#
(1)
Church
(1)
CIE
(1)
CO
(38)
Converter
(1)
cron
(1)
CSS
(23)
DMS
(1)
DVD
(1)
Eclipse
(1)
English
(1)
excel
(5)
Exchange
(4)
Failover
(1)
Fedora
(1)
FI
(57)
File Transfer
(1)
Firefox
(3)
FM
(2)
fourjs
(1)
Genero
(1)
gladiatus
(1)
google
(1)
Google Maps API
(2)
grep
(1)
Grub
(1)
HR
(2)
html
(23)
HTS
(8)
IE
(1)
IE 8
(1)
IIS
(1)
IMAP
(3)
Internet Explorer
(1)
java
(4)
JavaScript
(22)
jQuery
(6)
JSON
(1)
K3b
(1)
ldd
(1)
LED
(3)
Linux
(120)
Linux Mint
(4)
Load Balance
(1)
Microsoft
(2)
MIS
(2)
MM
(51)
MSSQL
(1)
MySQL
(27)
Network
(1)
NFS
(1)
Office
(1)
OpenSSL
(1)
Oracle
(131)
Outlook
(3)
PDF
(6)
Perl
(60)
PHP
(33)
PL/SQL
(1)
PL/SQL Developer
(1)
PM
(3)
Postfix
(2)
postfwd
(1)
PostgreSQL
(1)
PP
(50)
python
(5)
QM
(1)
Red Hat
(4)
Reporting Service
(28)
ruby
(11)
SAP
(234)
scp
(1)
SD
(16)
sed
(1)
Selenium
(3)
Selenium-WebDriver
(5)
shell
(5)
SQL
(4)
SQL server
(8)
sqlplus
(1)
SQuirreL SQL Client
(1)
SSH
(3)
SWOT
(3)
Symantec
(2)
T-SQL
(7)
Tera Term
(2)
tip
(1)
tiptop
(24)
Tomcat
(6)
Trouble Shooting
(1)
Tuning
(5)
Ubuntu
(37)
ufw
(1)
utf-8
(1)
VIM
(11)
Virtual Machine
(2)
VirtualBox
(1)
vnc
(3)
Web Service
(2)
wget
(1)
Windows
(19)
Windows
(1)
WM
(6)
Xvfb
(2)
youtube
(1)
yum
(2)
2016年3月9日 星期三
MySQL : Convert Integer to DateTime and DateTime to Integer
SELECT UNIX_TIMESTAMP('2016-03-14 18:00:00')
SELECT FROM_UNIXTIME(1457949600,'%Y %m %d %H %i %s')
2015年7月28日 星期二
MySQL時間相減,使用timestampdiff (Table schema is DataTime)
http://dreamtails.pixnet.net/blog/post/27976134-mysql%E6%99%82%E9%96%93%E7%9B%B8%E6%B8%9B,%E4%BD%BF%E7%94%A8timestampdiff-%28table-schema-is-datat
表格名稱為TimeTable.
分別有兩個columns,一個是downTime,一個是upTime.
而我們是以"分" minute來作輸出的單位, 也可使用"小時" hour為單位,或是"秒" second, "天" day, "月" month, "年" year.
mysql> select timestampdiff(minute,`downTime`,`upTime`) as Subtract from TimeTable;
表格名稱為TimeTable.
分別有兩個columns,一個是downTime,一個是upTime.
而我們是以"分" minute來作輸出的單位, 也可使用"小時" hour為單位,或是"秒" second, "天" day, "月" month, "年" year.
mysql> select timestampdiff(minute,`downTime`,`upTime`) as Subtract from TimeTable;
安裝 PHP/oci8/mysqli
1. OS version
[root@EIP-API-AP php-5.2.17]# lsb_release -a
LSB Version: :core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch
Distributor ID: CentOS
Description: CentOS release 6.2 (Final)
Release: 6.2
Codename: Final
2. Apache version
[root@EIP-API-AP php-5.2.17]# httpd -v
Server version: Apache/2.2.15 (Unix)
Server built: Oct 16 2014 14:48:21
3. PHP version
php-5.2.17
4. 拿掉/安裝 不要service
chkconfig iptables off
chkconfig postfix off
yum install vsftpd.x86_64 (vim /etc/vsftp/vsftpd.conf --> userlist_deny=NO)
5. OS command
yum install httpd-devel
yum install gcc
yum install libxml2-devel
yum install mysql-devel
yum install autoconf
cp -rp /usr/lib64/mysql/libmysqlclient.so.16.0.0 /usr/lib/libmysqlclient.so
./configure --with-apxs2=/usr/sbin/apxs --with-mysql
make
make test
make install
cp php.ini-recommended /usr/local/lib/php.ini
6. vim httpd.conf
<FilesMatch \.php$>
SetHandler application/x-httpd-php
</FilesMatch>
7. vim php.ini
short_open_tag=on (這樣<% 才認得,否則只能用 <?php)
8. OS command
service httpd restart
9. install oracle instant client
rpm -U oracle-instantclient12.1-basic-12.1.0.2.0-1.x86_64.rpm
rpm -U oracle-instantclient12.1-devel-12.1.0.2.0-1.x86_64.rpm
10. download oci8
ln -s /usr/lib/oracle/12.1/client64/lib/libclntsh.so.12.1 /usr/lib/oracle/12.1/client64/lib/libclntsh.so
tar zxvf oci8-2.0.8.tgz
cd oci8-2.0.8
phpize
./configure --with-oci8=shared,instantclient,/usr/lib/oracle/12.1/client64/lib
make
make install
11. vim /usr/local/lib/php.ini
extension_dir = "/usr/local/lib/php/extensions/no-debug-non-zts-20060613/"
extension=oci8.so
12. service httpd restart
13. mysqli installation
cd ~/Downloads/php-5.2.17/ext/mysqli/
phpize
./configure --prefix=/usr/local/mysqli --with-php-config=/usr/local/bin/php-config --with-mysqli=/usr/bin/mysql_config
make
make install
vim /usr/local/lib/php.ini (extension=mysqli.so)
14. phpinfo
check if oci8 installed
[root@EIP-API-AP php-5.2.17]# lsb_release -a
LSB Version: :core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch
Distributor ID: CentOS
Description: CentOS release 6.2 (Final)
Release: 6.2
Codename: Final
2. Apache version
[root@EIP-API-AP php-5.2.17]# httpd -v
Server version: Apache/2.2.15 (Unix)
Server built: Oct 16 2014 14:48:21
3. PHP version
php-5.2.17
4. 拿掉/安裝 不要service
chkconfig iptables off
chkconfig postfix off
yum install vsftpd.x86_64 (vim /etc/vsftp/vsftpd.conf --> userlist_deny=NO)
5. OS command
yum install httpd-devel
yum install gcc
yum install libxml2-devel
yum install mysql-devel
yum install autoconf
cp -rp /usr/lib64/mysql/libmysqlclient.so.16.0.0 /usr/lib/libmysqlclient.so
./configure --with-apxs2=/usr/sbin/apxs --with-mysql
make
make test
make install
cp php.ini-recommended /usr/local/lib/php.ini
6. vim httpd.conf
<FilesMatch \.php$>
SetHandler application/x-httpd-php
</FilesMatch>
7. vim php.ini
short_open_tag=on (這樣<% 才認得,否則只能用 <?php)
8. OS command
service httpd restart
9. install oracle instant client
rpm -U oracle-instantclient12.1-basic-12.1.0.2.0-1.x86_64.rpm
rpm -U oracle-instantclient12.1-devel-12.1.0.2.0-1.x86_64.rpm
10. download oci8
ln -s /usr/lib/oracle/12.1/client64/lib/libclntsh.so.12.1 /usr/lib/oracle/12.1/client64/lib/libclntsh.so
tar zxvf oci8-2.0.8.tgz
cd oci8-2.0.8
phpize
./configure --with-oci8=shared,instantclient,/usr/lib/oracle/12.1/client64/lib
make
make install
11. vim /usr/local/lib/php.ini
extension_dir = "/usr/local/lib/php/extensions/no-debug-non-zts-20060613/"
extension=oci8.so
12. service httpd restart
13. mysqli installation
cd ~/Downloads/php-5.2.17/ext/mysqli/
phpize
./configure --prefix=/usr/local/mysqli --with-php-config=/usr/local/bin/php-config --with-mysqli=/usr/bin/mysql_config
make
make install
vim /usr/local/lib/php.ini (extension=mysqli.so)
14. phpinfo
check if oci8 installed
從Oracle寫到MySQL時,中文變成亂碼
原因:
SHOW FULL COLUMNS FROM IMA_FILE;
可以看到 latin1_swedish_ci
+-----------+---------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+-----------+---------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
| ima01 | varchar(40) | utf8_unicode_ci | YES | MUL | NULL | | select,insert,update,references | |
| IMA02 | varchar(60) | latin1_swedish_ci | YES | | NULL | | select,insert,update,references | |
| ima021 | varchar(60) | utf8_unicode_ci | YES | | NULL | | select,insert,update,references | |
| IMA03 | varchar(20) | latin1_swedish_ci | YES | | NULL | | select,insert,update,references | |
...
這是亂碼的原因,改成utf8_unicode_ci
作法:
alter table IMA_FILE modify imaud02 varchar(40) CHARACTER SET utf8 COLLATE utf8_unicode_ci;
SHOW FULL COLUMNS FROM IMA_FILE;
可以看到 latin1_swedish_ci
+-----------+---------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+-----------+---------------+-------------------+------+-----+---------+-------+---------------------------------+---------+
| ima01 | varchar(40) | utf8_unicode_ci | YES | MUL | NULL | | select,insert,update,references | |
| IMA02 | varchar(60) | latin1_swedish_ci | YES | | NULL | | select,insert,update,references | |
| ima021 | varchar(60) | utf8_unicode_ci | YES | | NULL | | select,insert,update,references | |
| IMA03 | varchar(20) | latin1_swedish_ci | YES | | NULL | | select,insert,update,references | |
...
這是亂碼的原因,改成utf8_unicode_ci
作法:
alter table IMA_FILE modify imaud02 varchar(40) CHARACTER SET utf8 COLLATE utf8_unicode_ci;
2015年1月8日 星期四
遠端無法連線到MySQL Server ERROR 2003 (HY000)
http://blog.lyhdev.com/2006/07/mysql-server-error-2003-hy000.html
MySQL安裝後可能預設關閉遠端連線,因此在遠端進行連線時會出現這個錯誤:
ERROR 2003 (HY000): Can't connect to MySQL server on '***.***.***.***' (###)
如果必須透過遠端檢視或操作MySQL Server,需要修改一下設定檔,將bind-address、skip-networking的選項取消(如果被開啟的話)。
若這些設定沒有問題,仍沒辦法連線,再做一些其他檢查:
MySQL安裝後可能預設關閉遠端連線,因此在遠端進行連線時會出現這個錯誤:
ERROR 2003 (HY000): Can't connect to MySQL server on '***.***.***.***' (###)
如果必須透過遠端檢視或操作MySQL Server,需要修改一下設定檔,將bind-address、skip-networking的選項取消(如果被開啟的話)。
若這些設定沒有問題,仍沒辦法連線,再做一些其他檢查:
- netstat -nl grep 3306 (此數字是MySQL預設的連接埠)是否有0.0.0.0:3306出現,若沒有則表示MySQL server未啟動或仍未允許遠端連線
- iptables -L 檢視一下是否被防火牆擋掉
2014年7月17日 星期四
MySQL AUTOCOMMIT
http://php.net/manual/pt_BR/mysqli.commit.php
1. 使用PHP mysqli
1. 使用PHP mysqli
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE Language LIKE CountryLanguage Type=InnoDB");
/* set autocommit to off */$mysqli->autocommit(FALSE);
/* Insert some values */$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");$mysqli->query("INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");
/* commit transaction */$mysqli->commit();
/* drop table */$mysqli->query("DROP TABLE Language");
/* close connection */$mysqli->close();?>
2.
MySQL 預設都會啟動 Auto Commit, 要在 InnoDB 做 Transaction 有分兩種方法:
Test:
- BEGIN 直到 COMMIT, ROLLBACK 結束
- SET AUTOCOMMIT=0 直到 SET AUTOCOMMIT=1 結束
- 使用 BEGIN 是當下的做 Transaction 的功能, 一直到 COMMIT 或 ROLLBACK 為止.(之後一樣是會 AUTO COMMIT)
- 使用 SET AUTOCOMMIT 的話, 只要設 0 就是 "在這次的 Connection" 都當做 AUTOCOMMIT是關閉的, 不管做幾次 COMMIT, ROLLBACK 都一樣, 直到設為 1 才算開啟 AUTO COMMIT.
Test:
以上最好可以開兩個 Connection 互相 新、刪、改、查 測試.CREATE DATABASE innodb_test;
CREATE TABLE customers(a int, b char(20), index(a)) TYPE=InnoDB;
# 看 table 的狀態
SHOW TABLE STATUS FROM innodb_test LIKE 'customers'\G;
# BEGIN 的方法
BEGIN;
INSERT INTO customers VALUES(10, 'abc');
COMMIT; # 此 BEGIN Transaction 已在此結束
SELECT * FROM customers;
INSERT INTO customers VALUES(11, 'aaa');
ROLLBACK; # 此命令是無作用的, 已經不在 BEGIN 的範圍了, 資料會自動 COMMIT 進去.
SELECT * FROM customers;
# SET AUTOCOMMIT 的方法
# (注意: 其它 Connection 並不會因為這 Connection 設定而不 自動COMMIT)
SET AUTOCOMMIT=0;
INSERT INTO customers VALUES(15, 'def');
ROLLBACK;
INSERT INTO customers VALUES(16, 'ggg');
COMMIT;
SELECT * FROM customers;
# 回復每筆交易都會自動 COMMIT 的狀態
SET AUTOCOMMIT=1;
2014年7月9日 星期三
MySQL 計算 日期差距
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-sub
日期差距:datediff(sysdate(),欄位)
時間差距:timediff(sysdate(),欄位)
時間差距,只看小時:time_format(timediff(sysdate(),欄位),'%H')
日期差距:datediff(sysdate(),欄位)
時間差距:timediff(sysdate(),欄位)
時間差距,只看小時:time_format(timediff(sysdate(),欄位),'%H')
2014年7月2日 星期三
MySQL Query Cache
http://blog.shian.tw/mysql-query-cache.html
MySQL 也有 cache可以使用! 提高資料庫效能有很重要的效用,可以節約大量的 CPU 時間 ,並且設定也非常的簡單,但是MySQL的版本要4以上才有這功能!!
設定:
1. 修改 /etc/my.cnf 檔案
# vi /etc/my.cnf
2.在 [mysqld] 裡加入下面這2行
query_cache_size=2m
query_cache_type = 1
註:
query_cache_type = 1 => 全部使用 query cache
query_cache_type = 2 => 選擇性使用或不使用 query cache
SELECT SQL_CACHE ‘*’ FROM table => 使用 query cache
SELECT SQL_NO_CACHE ‘*’ FROM table => 不使用 query cache
query_cache_size=2m : 設定cache大小
3. 重啟MySQL
# /etc/local/mysql/share/mysql/mysql.server restart
指令:
1. 查看是否有開啟 query cache
mysql> SHOW VARIABLES LIKE ‘have_query_cache’;
have_query_cache = YES 表示有開啟
2.查看緩衝的情況
mysql> show status like ‘Qca%’;
3.伺服器執行了多少 SELECT 語句
mysql> show status like ‘Com_sel%’;
實際測試:
使用 phpmyadmin 一次查詢五萬筆資料
未使用 query cache
第一次

第二次

第三次

第四次

第五次

使用 query cache
第一次

第二次

第三次

第四次

第五次

結論:
經過測試後發覺有使用 query ache 後, 第一次之後的查詢時間就明顯的減少很多,雖然看起來好像沒有減少多少,但是當資料量多或是更多人使用查詢時,效果就可以明顯感覺出來了, 而且這個測試只是五萬筆資料測試而已,
MySQL Query Cache
設定:
1. 修改 /etc/my.cnf 檔案
# vi /etc/my.cnf
2.在 [mysqld] 裡加入下面這2行
query_cache_size=2m
query_cache_type = 1
註:
query_cache_type = 1 => 全部使用 query cache
query_cache_type = 2 => 選擇性使用或不使用 query cache
SELECT SQL_CACHE ‘*’ FROM table => 使用 query cache
SELECT SQL_NO_CACHE ‘*’ FROM table => 不使用 query cache
query_cache_size=2m : 設定cache大小
3. 重啟MySQL
# /etc/local/mysql/share/mysql/mysql.server restart
指令:
1. 查看是否有開啟 query cache
mysql> SHOW VARIABLES LIKE ‘have_query_cache’;
have_query_cache = YES 表示有開啟
2.查看緩衝的情況
mysql> show status like ‘Qca%’;
3.伺服器執行了多少 SELECT 語句
mysql> show status like ‘Com_sel%’;
實際測試:
使用 phpmyadmin 一次查詢五萬筆資料
未使用 query cache
第一次
第二次
第三次
第四次
第五次
使用 query cache
第一次
第二次
第三次
第四次
第五次
結論:
經過測試後發覺有使用 query ache 後, 第一次之後的查詢時間就明顯的減少很多,雖然看起來好像沒有減少多少,但是當資料量多或是更多人使用查詢時,效果就可以明顯感覺出來了, 而且這個測試只是五萬筆資料測試而已,
MySQL資料庫簡易效能調教
http://www.cc.ntu.edu.tw/chinese/epaper/0025/20130620_2510.html
作者:游子興 / 臺灣大學計算機及資訊網路中心網路組幹事
本文將介紹兩種方法來改善資料庫之效能:
一. 使用 MySQLTuner 進行 MySQL 之整體參數改善分析
官方網站: http://mysqltuner.pl/mysqltuner.pl
目前的版本Version 1.2.0,支援 MySQL 資料庫版本:
MySQL 3.23, 4.0, 4.1, 5.0, 5.1 (full support)
MySQL 5.4 (not fully tested, partially supported)
MySQL 6.0 (partial support)
此程式主要的功能在於蒐集運行中的MySQL 之 STATUS 與 Variable 相關變數來判斷並提供改善建議,程式本身使用 Perl Script Language 撰寫,因此不需安裝,僅需下載執行即可。
Step1. 指令: wget http://mysqltuner.pl/mysqltuner.pl
登入 Linux 後下載 MySQLTuner 之執行檔案 mysqltuner.pl

圖1. 下載 MySQLTuner 之執行檔案 mysqltuner.pl
Step2. 指令: chmod +x mysqltuner.pl
因下載檔案預設無 Execute 執行權限,使用 chmod +x 增加 Execute 權限。
圖2. 使用 chmod +x 增加 Execute 權限
Step3. 指令: ./mysqltuner.pl
不需安裝,直接執行程式即可進行測試。程式會先要求輸入 MySQL 具有管理權限之帳號密碼,在此輸入 root 及其密碼。

圖3. 執行 mysqltuner.pl 並輸入帳號密碼
Step4. 分析執行結果
完全不需設定與安裝就可產生分析結果,是不是非常簡單?
圖4. mysqltuner.pl 執行結果報告
接著我們將逐步分析執行的結果,各項目分成綠色[OK]與紅色[!!]來顯示,我們僅需針對 紅色[!!] 的結果來做改善與調教:
(1)[!!] Switch to 64-bit OS - MySQL cannot currently use all of your RAM
因為32bit 之定址能力最高只到2^32= 4,294,967,296 (4G),若該 Server設備已安裝超過4G 之實體記憶體,則建議使用 64bit 之作業系統才能使用所有的記憶體。
(2)[!!] InnoDB is enabled but isn't being used
[!!] BDB is enabled but isn't being used
上述兩行的意思是 InnoDB 與 BDB 狀態為啟用,但並未使用,因此可搭配報告中最後的建議:
-------- Recommendations -----------------------------------------------------
General recommendations:
Add skip-innodb to MySQL configuration to disable InnoDB
Add skip-bdb to MySQL configuration to disable BDB
增加兩行設定到 MySQL 之設定檔 ( 以CentOS 5.5 為例,預設檔案為: /etc/my.cnf)
skip-innodb
skip-bdb

圖5. 編輯設定檔 /etc/my.cnf
之後需重新啟動 MySQL
~# service mysqld restart
(3)[!!] User '@localhost' has no password set.
[!!] User '@localhost.localdomain' has no password set.
上述兩行是指資料庫中有兩個帳號沒有設定密碼,可能有 Security Issue,經檢查Table: mysql.user 後發現,此兩個帳號預設為MySQL 安裝時所建立,並無 User 名稱也無設定權限,如下圖,因此可忽略此訊息。
圖6. 觀察 Table: mysql.user 所設定之帳號密碼
(4)[!!] Key buffer size / total MyISAM indexes: 8.0M/1.1G
此處點出了一個很重要的問題,就是 Key buffer size 太小(僅有 8.0M),參考報告中最後的建議:
-------- Recommendations -----------------------------------------------------
Variables to adjust:
key_buffer_size (> 1.1G)
建議將 key_buffer_size 由 8.0 M 調整至 1.1G,原因在於 Key buffer size 的作用在於 Cache Table中的 indexes(索引),目前的索引佔據的空間已有 1.1G ( /var/lib/mysql/ 目錄中索引檔案 *.MYI 之檔案大小加總),因此建議至少調高與目前之 indexes 大小相符。設定方法是增加一行設定到設定檔: /etc/my.cnf
key_buffer_size= 1100000000
設定後一樣需重新啟動 MySQL。
(5)[!!] Query cache is disabled
Query cache的作用在於 Cache 查詢(Query) 之結果以供後續相同的查詢使用,由變數query_cache_size 所控制,預設值為0,因此預設為 disabled,參考報告中最後的建議:
-------- Recommendations -----------------------------------------------------
Variables to adjust:
query_cache_size (>= 8M)
增加一行設定到 /etc/my.cnf
query_cache_size = 8000000
設定後一樣需重新啟動 MySQL。
(6)[!!] Thread cache is disabled
Thread cache的作用在於每次建立新的連線 (Thread) 時,會先看Thread cache 中是否有可用的 Thread,若有則直接取用,若無才重新建立新的連線,如此可減少CPU Loading。若系統常有大量且短暫的連線發生,則適當的設定此參數非常重要。由變數thread_cache_size 所控制,預設值為0,因此預設為 disabled,參考報告中最後的建議:
-------- Recommendations -----------------------------------------------------
Variables to adjust:
thread_cache_size (start at 4)
增加一行設定到 /etc/my.cnf
thread_cache_size=4
設定後一樣需重新啟動 MySQL,之後可用指令:
SHOW STATUS like 'Threads_%';
觀察變數 Threads_created 若已不會再持續增加,表示thread_cache_size已經足夠。

圖7. 觀察 STATUS 中 Threads 開頭之變數
(7)[!!] Connections aborted: 14%
此訊息搭配報告中最後的建議:
-------- Recommendations -----------------------------------------------------
General recommendations:
Your applications are not closing MySQL connections properly
表示時常有連上 MySQL 之連線不正常斷線,一般正常的斷線程式需呼叫mysql_close() 來正常關閉,可搭配指令:
SHOW STATUS like 'Aborted_%';

圖8. 觀察 STATUS 中 Aborted 開頭之變數
可觀察變數Aborted_clients, Aborted_connects 是否已經不再持續增加,來判斷是否已經改善。
(8)General recommendations:
MySQL started within last 24 hours - recommendations may be inaccurate
Enable the slow query log to troubleshoot bad queries
報告中最後還有兩個建議:
1.因為MySQLTuner 是利用 MySQL 系統中之 STATUS 與 Variable 相關變數來判斷並提供建議,因此必須有足夠的執行時間來蒐集資料庫運作的效能,因此若資料庫運作時間不到 24小時,則會出現警告訊息。
2.系統建議可開啟slow query log 之功能來記錄執行特別久的 SQL,以供後續的分析,方法為增加兩行設定到 /etc/my.cnf
log_slow_queries= mysqld-slow.log
long_query_time= 10
設定後一樣需重新啟動 MySQL。
log_slow_queries 指定 slow query log 存放之檔名,預設存在 /var/lib/mysql/ 目錄下。
long_query_time 設定超過幾秒之 SQL Query 會被記錄在 log_slow_queries 之log 檔中,系統預設值為 10秒。
二. 使用 Explain Plan 進行個別 SQL 調教
當資料庫的效能不符需求時,大部分發生在特定的 SQL 語句拖慢整個系統效能,蒐集這些 SQL 的方法本文提供兩種,一種就是用先前介紹的slow query log 方法記錄執行超過特定時間的 SQL,另一種方法是即時觀察系統目前之 Performance。
Step1. 指令: top

圖9. 使用 top 指令觀察系統資源使用情形
觀察CPU Usage%排名第一就是 mysqld,而且佔用了 99.9% 的 CPU Resource。
Step2. login MySQL,使用指令:
SHOW FULL PROCESSLIST;

圖10. 使用 SHOW FULL PROCESSLIST指令之執行結果
可看到目前正在執行之所有 SQL 語句,特別注意其中Process Id 8,Command 顯示 Query 表示正在執行,Time 欄位顯示已經執行了 117秒,Info 中有正在執行的 SQL 語句。
在得到了 SQL 語句之後,接著使用 Explain 觀察是否有可以改善之處.

圖11. 使用 Explain指令之執行結果
簡單說明各欄位之意義:
(1)select_type: SELECT 使用之語法型態。SIMPLE表示為簡單的查詢語句,也就是沒有 UNION、Subquery 等語法在此查詢中。
(2)table: 此 SQL 查詢所用到的 table,此案例因為使用了 Join因此用到了兩個 table。
(3)type: 使用何種類型進行查詢。最優至最差的類型為:
system -> const -> eq_ref -> ref -> fulltext -> ref_or_null -> index_merge -> unique_subquery -> index_subquery -> range -> index -> ALL
此案例值為”ALL”,也就是最差之狀況。
(4)possible_keys:可能使用的索引欄位。若為NULL 表示無索引可使用。
(5)key:實際使用的索引欄位。若為NULL 表示無索引可使用。
(6)key_len:使用的索引長度。
(7)rows: SQL 必須搜尋的資料筆數。
(8)Extra:
Using where: SQL 中有使用WHERE 語句來限制查詢的範圍。
Using temporary : MySQL 必須建立一個臨時的 Table 來儲存查詢結果,通常發生在 SQL 語法中有 Order By 或 GROUP BY。
Using filesort:MySQL必須進行額外的步驟來進行 ORDER BY 之排序作業。
此段 SQL 執行之狀況,也可參考前面第一部分之介紹啟用slow query log,log 記錄檔中顯示:
/var/lib/mysql/mysqld-slow.log

圖12. slow query log 記錄之內容
此 SQL 共花了 121 秒才執行完成。
由上述的Explain 分析可知,此段 SQL 並未使用任何的索引,我們再次分析此段 SQL 中 JOIN 與 WHERE 條件中所出現的欄位:
LEFT JOIN … ON aruba.ArubaLocationID = arubalocationmap.ArubaLocationID
WHERE (YEAR(`AcctStartTime`) > '2012'…..
AND aruba.`ArubaLocationID` LIKE '113.%' ….
其中特別注意的是 JOIN 語法中兩個 Table 的對應欄位都必須加上索引才有作用,因此我們決定針對
Table: aruba 增加 ArubaLocationID, AcctStartTime 兩個欄位的索引
Table: arubalocationmap增加 ArubaLocationID 一個欄位的索引
建立索引的語法如下:
CREATE Index ArubaLocationID On aruba (ArubaLocationID);
CREATE Index AcctStartTime On aruba (AcctStartTime);
CREATE Index ArubaLocationID On arubalocationmap (ArubaLocationID);
索引建立後,我們再次使用 Explain 觀察此段 SQL 執行之情況:


圖13. 使用 Explain指令之執行結果
由 type, key 欄位發現新建的索引已經發揮作用。
再次檢查 slow query log,log 記錄檔中顯示:
/var/lib/mysql/mysqld-slow.log

圖14. slow query log 記錄之內容
執行時間由 121 秒減少為 13秒,僅需原來 1/10的時間,由此可知建立正確的索引將有非常大幅度之改善。
結論
MySQL 是個功能強大的資料庫,尤其搭配 PHP 程式後可做出各式的動態網頁資料庫進行各類的應用,本文拋磚引玉使用簡單的範例來調整並改善資料庫的效能,投入的時間與改善並不需要太久,但卻能有十倍之 執行效能改善,這樣的改善效益是非常令人期待的。
參考資料
1. MySQLTuner http://mysqltuner.pl/
2. Explain plan http://dev.mysql.com/doc/refman/5.0/en/explain-output.html 3.query cache size (query_cache_size) http://dev.mysql.com/doc/refman/5.0/en/query-cache-configuration.html
作者:游子興 / 臺灣大學計算機及資訊網路中心網路組幹事
MySQL 資料庫是個使用廣泛的 Open Source 資料庫,本文以實際的範例搭配淺顯的說明與實作,一步一步進行效能之調教,而使大部分非科班出生之 MySQL 資料庫管理人員得以輕鬆應付與日遽增大量的資料。
前言
MySQL 是一個Open Source的中小型關連式資料庫,因本身簡單易用且大部分的 Linux Distribution 皆有提供 MySQL Package,因此許多學術單位與中小型企業十分愛用。但隨著時間增加,資料量也持續增加,如何作效能之調教與改善 (Performance Tuning) 對於可能非科班出生之資料庫管理員 DBA,則成為一個棘手的問題。 本文將介紹兩種方法來改善資料庫之
MySQL
是一個Open Source的中小型關連式資料庫,因本身簡單易用且大部分的 Linux Distribution 皆有提供 MySQL
Package,因此許多學術單位與中小型企業十分愛用。但隨著時間增加,資料量也持續增加,如何作效能之調教與改善 (Performance
Tuning) 對於可能非科班出生之資料庫管理員 DBA,則成為一個棘手的問題。 MySQL 是一個Open Source的中小型關連式資料庫,因本身簡單易用且大部分的 Linux Distribution 皆有提供 MySQL Package,因此許多學術單位與中小型企業十分愛用。但隨著時間增加,資料量也持續增加,如何作效能之調教與改善 (Performance Tuning) 對於可能非科班出生之資料庫管理員 DBA,則成為一個棘手的問題。 本文將介紹兩種方法來改善資料庫之
本文將介紹兩種方法來改善資料庫之效能:
- 使用 MySQLTuner 進行 MySQL 之整體參數改善分析
- 使用 Explain Plan 進行個別 SQL 調教
一. 使用 MySQLTuner 進行 MySQL 之整體參數改善分析
官方網站: http://mysqltuner.pl/mysqltuner.pl
目前的版本Version 1.2.0,支援 MySQL 資料庫版本:
MySQL 3.23, 4.0, 4.1, 5.0, 5.1 (full support)
MySQL 5.4 (not fully tested, partially supported)
MySQL 6.0 (partial support)
此程式主要的功能在於蒐集運行中的MySQL 之 STATUS 與 Variable 相關變數來判斷並提供改善建議,程式本身使用 Perl Script Language 撰寫,因此不需安裝,僅需下載執行即可。
Step1. 指令: wget http://mysqltuner.pl/mysqltuner.pl
登入 Linux 後下載 MySQLTuner 之執行檔案 mysqltuner.pl
圖1. 下載 MySQLTuner 之執行檔案 mysqltuner.pl
Step2. 指令: chmod +x mysqltuner.pl
因下載檔案預設無 Execute 執行權限,使用 chmod +x 增加 Execute 權限。
圖2. 使用 chmod +x 增加 Execute 權限
Step3. 指令: ./mysqltuner.pl
不需安裝,直接執行程式即可進行測試。程式會先要求輸入 MySQL 具有管理權限之帳號密碼,在此輸入 root 及其密碼。
圖3. 執行 mysqltuner.pl 並輸入帳號密碼
Step4. 分析執行結果
完全不需設定與安裝就可產生分析結果,是不是非常簡單?
圖4. mysqltuner.pl 執行結果報告
接著我們將逐步分析執行的結果,各項目分成綠色[OK]與紅色[!!]來顯示,我們僅需針對 紅色[!!] 的結果來做改善與調教:
(1)[!!] Switch to 64-bit OS - MySQL cannot currently use all of your RAM
因為32bit 之定址能力最高只到2^32= 4,294,967,296 (4G),若該 Server設備已安裝超過4G 之實體記憶體,則建議使用 64bit 之作業系統才能使用所有的記憶體。
(2)[!!] InnoDB is enabled but isn't being used
[!!] BDB is enabled but isn't being used
上述兩行的意思是 InnoDB 與 BDB 狀態為啟用,但並未使用,因此可搭配報告中最後的建議:
-------- Recommendations -----------------------------------------------------
General recommendations:
Add skip-innodb to MySQL configuration to disable InnoDB
Add skip-bdb to MySQL configuration to disable BDB
增加兩行設定到 MySQL 之設定檔 ( 以CentOS 5.5 為例,預設檔案為: /etc/my.cnf)
skip-innodb
skip-bdb
圖5. 編輯設定檔 /etc/my.cnf
之後需重新啟動 MySQL
~# service mysqld restart
(3)[!!] User '@localhost' has no password set.
[!!] User '@localhost.localdomain' has no password set.
上述兩行是指資料庫中有兩個帳號沒有設定密碼,可能有 Security Issue,經檢查Table: mysql.user 後發現,此兩個帳號預設為MySQL 安裝時所建立,並無 User 名稱也無設定權限,如下圖,因此可忽略此訊息。
圖6. 觀察 Table: mysql.user 所設定之帳號密碼
(4)[!!] Key buffer size / total MyISAM indexes: 8.0M/1.1G
此處點出了一個很重要的問題,就是 Key buffer size 太小(僅有 8.0M),參考報告中最後的建議:
-------- Recommendations -----------------------------------------------------
Variables to adjust:
key_buffer_size (> 1.1G)
建議將 key_buffer_size 由 8.0 M 調整至 1.1G,原因在於 Key buffer size 的作用在於 Cache Table中的 indexes(索引),目前的索引佔據的空間已有 1.1G ( /var/lib/mysql/ 目錄中索引檔案 *.MYI 之檔案大小加總),因此建議至少調高與目前之 indexes 大小相符。設定方法是增加一行設定到設定檔: /etc/my.cnf
key_buffer_size= 1100000000
設定後一樣需重新啟動 MySQL。
(5)[!!] Query cache is disabled
Query cache的作用在於 Cache 查詢(Query) 之結果以供後續相同的查詢使用,由變數query_cache_size 所控制,預設值為0,因此預設為 disabled,參考報告中最後的建議:
-------- Recommendations -----------------------------------------------------
Variables to adjust:
query_cache_size (>= 8M)
增加一行設定到 /etc/my.cnf
query_cache_size = 8000000
設定後一樣需重新啟動 MySQL。
(6)[!!] Thread cache is disabled
Thread cache的作用在於每次建立新的連線 (Thread) 時,會先看Thread cache 中是否有可用的 Thread,若有則直接取用,若無才重新建立新的連線,如此可減少CPU Loading。若系統常有大量且短暫的連線發生,則適當的設定此參數非常重要。由變數thread_cache_size 所控制,預設值為0,因此預設為 disabled,參考報告中最後的建議:
-------- Recommendations -----------------------------------------------------
Variables to adjust:
thread_cache_size (start at 4)
增加一行設定到 /etc/my.cnf
thread_cache_size=4
設定後一樣需重新啟動 MySQL,之後可用指令:
SHOW STATUS like 'Threads_%';
觀察變數 Threads_created 若已不會再持續增加,表示thread_cache_size已經足夠。
圖7. 觀察 STATUS 中 Threads 開頭之變數
(7)[!!] Connections aborted: 14%
此訊息搭配報告中最後的建議:
-------- Recommendations -----------------------------------------------------
General recommendations:
Your applications are not closing MySQL connections properly
表示時常有連上 MySQL 之連線不正常斷線,一般正常的斷線程式需呼叫mysql_close() 來正常關閉,可搭配指令:
SHOW STATUS like 'Aborted_%';
圖8. 觀察 STATUS 中 Aborted 開頭之變數
可觀察變數Aborted_clients, Aborted_connects 是否已經不再持續增加,來判斷是否已經改善。
(8)General recommendations:
MySQL started within last 24 hours - recommendations may be inaccurate
Enable the slow query log to troubleshoot bad queries
報告中最後還有兩個建議:
1.因為MySQLTuner 是利用 MySQL 系統中之 STATUS 與 Variable 相關變數來判斷並提供建議,因此必須有足夠的執行時間來蒐集資料庫運作的效能,因此若資料庫運作時間不到 24小時,則會出現警告訊息。
2.系統建議可開啟slow query log 之功能來記錄執行特別久的 SQL,以供後續的分析,方法為增加兩行設定到 /etc/my.cnf
log_slow_queries= mysqld-slow.log
long_query_time= 10
設定後一樣需重新啟動 MySQL。
log_slow_queries 指定 slow query log 存放之檔名,預設存在 /var/lib/mysql/ 目錄下。
long_query_time 設定超過幾秒之 SQL Query 會被記錄在 log_slow_queries 之log 檔中,系統預設值為 10秒。
二. 使用 Explain Plan 進行個別 SQL 調教
當資料庫的效能不符需求時,大部分發生在特定的 SQL 語句拖慢整個系統效能,蒐集這些 SQL 的方法本文提供兩種,一種就是用先前介紹的slow query log 方法記錄執行超過特定時間的 SQL,另一種方法是即時觀察系統目前之 Performance。
Step1. 指令: top
圖9. 使用 top 指令觀察系統資源使用情形
觀察CPU Usage%排名第一就是 mysqld,而且佔用了 99.9% 的 CPU Resource。
Step2. login MySQL,使用指令:
SHOW FULL PROCESSLIST;
圖10. 使用 SHOW FULL PROCESSLIST指令之執行結果
可看到目前正在執行之所有 SQL 語句,特別注意其中Process Id 8,Command 顯示 Query 表示正在執行,Time 欄位顯示已經執行了 117秒,Info 中有正在執行的 SQL 語句。
在得到了 SQL 語句之後,接著使用 Explain 觀察是否有可以改善之處.
圖11. 使用 Explain指令之執行結果
簡單說明各欄位之意義:
(1)select_type: SELECT 使用之語法型態。SIMPLE表示為簡單的查詢語句,也就是沒有 UNION、Subquery 等語法在此查詢中。
(2)table: 此 SQL 查詢所用到的 table,此案例因為使用了 Join因此用到了兩個 table。
(3)type: 使用何種類型進行查詢。最優至最差的類型為:
system -> const -> eq_ref -> ref -> fulltext -> ref_or_null -> index_merge -> unique_subquery -> index_subquery -> range -> index -> ALL
此案例值為”ALL”,也就是最差之狀況。
(4)possible_keys:可能使用的索引欄位。若為NULL 表示無索引可使用。
(5)key:實際使用的索引欄位。若為NULL 表示無索引可使用。
(6)key_len:使用的索引長度。
(7)rows: SQL 必須搜尋的資料筆數。
(8)Extra:
Using where: SQL 中有使用WHERE 語句來限制查詢的範圍。
Using temporary : MySQL 必須建立一個臨時的 Table 來儲存查詢結果,通常發生在 SQL 語法中有 Order By 或 GROUP BY。
Using filesort:MySQL必須進行額外的步驟來進行 ORDER BY 之排序作業。
此段 SQL 執行之狀況,也可參考前面第一部分之介紹啟用slow query log,log 記錄檔中顯示:
/var/lib/mysql/mysqld-slow.log
圖12. slow query log 記錄之內容
此 SQL 共花了 121 秒才執行完成。
由上述的Explain 分析可知,此段 SQL 並未使用任何的索引,我們再次分析此段 SQL 中 JOIN 與 WHERE 條件中所出現的欄位:
LEFT JOIN … ON aruba.ArubaLocationID = arubalocationmap.ArubaLocationID
WHERE (YEAR(`AcctStartTime`) > '2012'…..
AND aruba.`ArubaLocationID` LIKE '113.%' ….
其中特別注意的是 JOIN 語法中兩個 Table 的對應欄位都必須加上索引才有作用,因此我們決定針對
Table: aruba 增加 ArubaLocationID, AcctStartTime 兩個欄位的索引
Table: arubalocationmap增加 ArubaLocationID 一個欄位的索引
建立索引的語法如下:
CREATE Index ArubaLocationID On aruba (ArubaLocationID);
CREATE Index AcctStartTime On aruba (AcctStartTime);
CREATE Index ArubaLocationID On arubalocationmap (ArubaLocationID);
索引建立後,我們再次使用 Explain 觀察此段 SQL 執行之情況:
圖13. 使用 Explain指令之執行結果
由 type, key 欄位發現新建的索引已經發揮作用。
再次檢查 slow query log,log 記錄檔中顯示:
/var/lib/mysql/mysqld-slow.log
圖14. slow query log 記錄之內容
執行時間由 121 秒減少為 13秒,僅需原來 1/10的時間,由此可知建立正確的索引將有非常大幅度之改善。
結論
MySQL 是個功能強大的資料庫,尤其搭配 PHP 程式後可做出各式的動態網頁資料庫進行各類的應用,本文拋磚引玉使用簡單的範例來調整並改善資料庫的效能,投入的時間與改善並不需要太久,但卻能有十倍之 執行效能改善,這樣的改善效益是非常令人期待的。
參考資料
1. MySQLTuner http://mysqltuner.pl/
2. Explain plan http://dev.mysql.com/doc/refman/5.0/en/explain-output.html 3.query cache size (query_cache_size) http://dev.mysql.com/doc/refman/5.0/en/query-cache-configuration.html
MySQL 設定檔優化-cache
http://article.denniswave.com/6345
From:http://www.bsdlover.cn/html/89/n-1789.html
查詢Cache狀態
例如現在我們查詢的結果如下:
設置為64M cache內存後
自由內存塊看起來變小了。
是因為現在自由內存塊是一個整塊,而以前的內存塊都是分散的小塊。而因為重建了cache區,Qcache_queries_in_cache 變量變小了。因為此操作重新建立了cache內存區,所有數據重新緩存,在運行一兩天後我們再看此數據。如果變大了,說明增大cache內存區域是有效 的,如果和以前數據差不多說明增加的內存並沒有實際起到多大的作用。
有人會覺得如果我將cache內存設置的非常大,然後將cache_limit設置成0,那麼所有查詢都會被緩存了。理論上是這樣,但是一台數據庫 服務器的查詢非常多,如果連查詢單條數據都要緩存,那麼內存再大也會不夠的。到時候老的內容就會被交換出去,當cache內存使用滿的時候,就會不停的有 新查詢進來將老查詢替換出去。
這樣導致兩個結果:一個是內存顛簸,效率反而下降;第二個是cache內存的小碎塊增多,內存利用率降低。如果是只有內容很少的小庫,並且查詢率不高,是可以使用這種方法提高響應速度。但是如果是實際生產環境,數據量會比較大,還是需要按照最佳比例來配置。
而不同的應用不同的數據量會有不同的搭配,這點大家不要看網上的優化配置隨便的填寫,還是要時時的查看mysql的狀態進行調整。即便是這個月調整好的優化參數,到了下個月業務不同,數據量增加,也會需要調整的。
From:http://www.bsdlover.cn/html/89/n-1789.html
- thread_concurrency 數量設置為CPU核心數量的兩倍.
- thread_cache_size 按照內存大小來設置, 1G=8, 2G=16, 3G=32, >3G=64
- wait_timeout 超時時間,如果連接數比較大,可以減少此參數的值,我使用的是10
- max_connections 最大連接數,mysql實際允許連接數的值是max_connections+1,按照系統庫不同而有不同性能。一般是500~1000,MySQL AB提供的linux靜態庫可以達到4000。
- query_cache_size 查詢緩衝,默認是0,所以必須打開以提高mysql性能,其本身需要40K來保存結構數據。所以不能設置的太小,初期可以設置成32M,然後根據實際運行情況另行調整。
- query_cache_type 指定查詢緩衝的類型:
- query_cache_limit 允許進入查詢緩衝區的最小數據大小,默認值是1MB,可以修改的小一點以滿足更多查詢的需求。但是如果設置的過於小,則會導致很多新的小查詢的結果將原有的查詢結果交換出去,增加系統的顛簸。
0是關閉
1是緩衝除了使用 SELECT SQL_NO_CACHE 語句指明了不需要緩衝的數據意外的所有查詢
2是只緩衝 SELECT SQL_CACHE 指定的查詢
一般設置為1
- 查詢mysql服務器相關狀態數據 >SHOW STATUS;
- 查詢mysql服務器相關配置選項 >SHOW VARIABLES;
- 整理查詢緩衝區裡的碎片 >flush query cache;
- 刪除查詢緩衝區裡的所有內容 >reset query cache;
- 設置mysql參數 >SET GLOBAL;
- 查詢mysql當前執行的sql語句 >show processlist;
- 查詢緩存中的空閒內存塊的數目 Qcache_free_blocks
- 查詢緩存的空閒內存總數 Qcache_free_memory
- 緩存採樣數數目 Qcache_hits
- 被加入到緩存中的查詢數目 Qcache_inserts
- 因為缺少內存而被從緩存中刪除的查詢數目 Qcache_lowmem_prunes
- 沒有被緩存的查詢數目 (不能被緩存的,或由於 QUERY_CACHE_TYPE) Qcache_not_cached
- 在緩存中已註冊的查詢數目 Qcache_queries_in_cache
- 查詢緩存中的塊的總數目 Qcache_total_blocks
查詢Cache狀態
如果Qcache_lowmem_prunes非常大,說明因為內存不足而被交換出cache的數據很多.如果增加內存.可以保證較小的交換次數以及較高的命中率>SHOW STATUS LIKE 'Qcache%';
例如現在我們查詢的結果如下:
| Qcache_free_blocks | 1234 |
| Qcache_free_memory | 25957504 |
| Qcache_hits | 55771119 |
| Qcache_inserts | 7441153 |
| Qcache_lowmem_prunes | 28332 |
| Qcache_not_cached | 1233788 |
| Qcache_queries_in_cache | 4810 |
| Qcache_total_blocks | 11038 |
>set global query_cache_size=67108864;
| Qcache_free_blocks | 1 |
| Qcache_free_memory | 66623616 |
| Qcache_hits | 55788258 |
| Qcache_inserts | 7445445 |
| Qcache_lowmem_prunes | 28332 |
| Qcache_not_cached | 1234057 |
| Qcache_queries_in_cache | 183 |
| Qcache_total_blocks | 392 |
是因為現在自由內存塊是一個整塊,而以前的內存塊都是分散的小塊。而因為重建了cache區,Qcache_queries_in_cache 變量變小了。因為此操作重新建立了cache內存區,所有數據重新緩存,在運行一兩天後我們再看此數據。如果變大了,說明增大cache內存區域是有效 的,如果和以前數據差不多說明增加的內存並沒有實際起到多大的作用。
有人會覺得如果我將cache內存設置的非常大,然後將cache_limit設置成0,那麼所有查詢都會被緩存了。理論上是這樣,但是一台數據庫 服務器的查詢非常多,如果連查詢單條數據都要緩存,那麼內存再大也會不夠的。到時候老的內容就會被交換出去,當cache內存使用滿的時候,就會不停的有 新查詢進來將老查詢替換出去。
這樣導致兩個結果:一個是內存顛簸,效率反而下降;第二個是cache內存的小碎塊增多,內存利用率降低。如果是只有內容很少的小庫,並且查詢率不高,是可以使用這種方法提高響應速度。但是如果是實際生產環境,數據量會比較大,還是需要按照最佳比例來配置。
而不同的應用不同的數據量會有不同的搭配,這點大家不要看網上的優化配置隨便的填寫,還是要時時的查看mysql的狀態進行調整。即便是這個月調整好的優化參數,到了下個月業務不同,數據量增加,也會需要調整的。
2014年6月5日 星期四
change mysql default character set to UTF8 in my.cnf
http://stackoverflow.com/questions/3513773/change-mysql-default-character-set-to-utf8-in-my-cnf
[mysqld]
init_connect='SET collation_connection = utf8_unicode_ci'
init_connect='SET NAMES utf8'
character-set-server = utf8
collation-server = utf8_unicode_ci
[client]
default-character-set = utf8
[mysqld]
init_connect='SET collation_connection = utf8_unicode_ci'
init_connect='SET NAMES utf8'
character-set-server = utf8
collation-server = utf8_unicode_ci
[client]
default-character-set = utf8
2014年5月29日 星期四
如何設定MySQL column 的character set and collation
alter table mobile.IMA_FILE modify ima01 varchar(40) character set utf8 collate utf8_unicode_ci;
2014年5月18日 星期日
MySQL 優化大全:設定 my.cnf 優化指南
http://coldly74.blog.fc2.com/blog-entry-6.html
開啟 MySQL query cache
如果 MySQL server 是非常繁忙,可以開啟 query cache 以加速回應時間,開啟方法可以在 my.cnf 裡面加入以下項目:
(Redhat 下面是 /etc/my.cnf;Debian 是在 etc/mysql/my.cnf)
query_cache_size = 268435456
query_cache_type = 1
query_cache_limit = 1048576
開啟 MySQL query cache
如果 MySQL server 是非常繁忙,可以開啟 query cache 以加速回應時間,開啟方法可以在 my.cnf 裡面加入以下項目:
(Redhat 下面是 /etc/my.cnf;Debian 是在 etc/mysql/my.cnf)
query_cache_size = 268435456
query_cache_type = 1
query_cache_limit = 1048576
2014年5月14日 星期三
MySQL 的 "SET NAMES xxx" 字元編碼問題分析
http://www.vixual.net/blog/archives/310
近來接受 BBT 的培訓,做一個投票系統。系統程式碼倒不是很難,但是我的時間主要花費在了研究字符集和編碼上面。MySQL 和 Apache 兩個系統的編碼(字符集)問題讓我費勁腦筋,吃盡苦頭。網上對這些問題的解決比較零散,比較片面,大部分是提供解決方法,卻不說為什麼。於是我將這幾天收 穫總結一下,避免後來者再走彎路。這篇文章對 PHP 編寫有一點幫助(看完你就知道,怎樣讓你的 PHP 程式在大部分空間提供商的伺服器裡顯示正常),但是更多幫助在於網路伺服器的架設和設置。
先說 MySQL 的字符集問題。Windows 下可透過修改 my.ini 內的
到 MySQL 命令行輸入 “SET NAMES UTF8;”,然後執行 “show variables like 'character%';”,發現原來為 latin1 的那些變數 “character_set_client”、”character_set_connection”、 ”character_set_results” 的值全部變為 utf8 了,原來是這 3 個變數在搗蛋。
查閱手冊,上面那句等於:
資料輸入路徑:client → connection → server;
資料輸出路徑:server → connection → results。
換句話說,每個路徑要經過 3 次改變字符集編碼。以出現亂碼的輸出為例,server 裡 utf8 的資料,傳入 connection 轉為 latin1,傳入 results 轉為 latin1,utf-8 頁面又把 results 轉過來。如果兩種字符集不相容,比如 latin1 和 utf8,轉化過程就為不可逆的,破壞性的。所以就轉不回來了。
但這裡要聲明一點,”SET NAMES UTF8″ 作用只是臨時的,MySQL 重啟後就恢復預設了。
接下來就說到 MySQL 在伺服器上的配置問題了。豈不是我們每次對資料庫讀寫都得加上 “SET NAMES UTF8″,以保證資料傳輸的編碼一致?能不能透過配置 MySQL 來達到那三個變數預設就為我們要想的字符集?手冊上沒說,我在網上也沒找到答案。所以,從伺服器配置的角度而言,是沒辦法省略掉那行程式碼的。
總結:為了讓你的網頁能在更多的伺服器上正常地顯示,還是加上 “SET NAMES UTF8″ 吧,即使你現在沒有加上這句也能正常瀏覽。
問題多多,多謝指正!
[轉載]MySQL 的 "SET NAMES xxx" 字元編碼問題分析
轉載自: PHPChina近來接受 BBT 的培訓,做一個投票系統。系統程式碼倒不是很難,但是我的時間主要花費在了研究字符集和編碼上面。MySQL 和 Apache 兩個系統的編碼(字符集)問題讓我費勁腦筋,吃盡苦頭。網上對這些問題的解決比較零散,比較片面,大部分是提供解決方法,卻不說為什麼。於是我將這幾天收 穫總結一下,避免後來者再走彎路。這篇文章對 PHP 編寫有一點幫助(看完你就知道,怎樣讓你的 PHP 程式在大部分空間提供商的伺服器裡顯示正常),但是更多幫助在於網路伺服器的架設和設置。
先說 MySQL 的字符集問題。Windows 下可透過修改 my.ini 內的
# CLIENT SECTION [mysql] default-character-set=utf8 # SERVER SECTION [mysqld] default-character-set=utf8這兩個字段來更改資料庫的預設字符集。第一個是客戶端預設的字符集,第二個是伺服器端預設的字符集。假設我們把兩個都設為 utf8,然後在MySQL Command Line 裡面輸入 “show variables like 'character%';”,可看到如下結果:
character_set_client latin1 character_set_connection latin1 character_set_database utf8 character_set_results latin1 character_set_server utf8 character_set_system utf8其中的 utf8 隨著我們上面的設置而改動。此時,要是我們透過採用 UTF-8 的 PHP 程式從資料庫裡讀取資料,很有可能是一串 “?????” 或者是其他亂碼。網上查了半天,解決辦法倒是簡單,在連結資料庫之後,讀取資料之前,先執行一項查詢 “SET NAMES UTF8″,即在 PHP 裡為
mysql_query("SET NAMES UTF8");
即可顯示正常(只要資料庫裡資料的字元正常)。為什麼會這樣?這句查詢 “SET NAMES UTF8″ 到底是什麼作用?到 MySQL 命令行輸入 “SET NAMES UTF8;”,然後執行 “show variables like 'character%';”,發現原來為 latin1 的那些變數 “character_set_client”、”character_set_connection”、 ”character_set_results” 的值全部變為 utf8 了,原來是這 3 個變數在搗蛋。
查閱手冊,上面那句等於:
SET character_set_client = utf8; SET character_set_results = utf8; SET character_set_connection = utf8;看看這 3 個變數的作用:
資料輸入路徑:client → connection → server;
資料輸出路徑:server → connection → results。
換句話說,每個路徑要經過 3 次改變字符集編碼。以出現亂碼的輸出為例,server 裡 utf8 的資料,傳入 connection 轉為 latin1,傳入 results 轉為 latin1,utf-8 頁面又把 results 轉過來。如果兩種字符集不相容,比如 latin1 和 utf8,轉化過程就為不可逆的,破壞性的。所以就轉不回來了。
但這裡要聲明一點,”SET NAMES UTF8″ 作用只是臨時的,MySQL 重啟後就恢復預設了。
接下來就說到 MySQL 在伺服器上的配置問題了。豈不是我們每次對資料庫讀寫都得加上 “SET NAMES UTF8″,以保證資料傳輸的編碼一致?能不能透過配置 MySQL 來達到那三個變數預設就為我們要想的字符集?手冊上沒說,我在網上也沒找到答案。所以,從伺服器配置的角度而言,是沒辦法省略掉那行程式碼的。
總結:為了讓你的網頁能在更多的伺服器上正常地顯示,還是加上 “SET NAMES UTF8″ 吧,即使你現在沒有加上這句也能正常瀏覽。
問題多多,多謝指正!
參考網頁
- PHPChina: Apache和PHP網頁的編碼問題分析
- MySQL: Character Set Support
2014年4月30日 星期三
Access denied for user 'root'@'localhost' (using password: NO)'
http://magicsun.pixnet.net/blog/post/25768313-mysqladmin%3A-connect-to-server-at-%27localhost%27-failed-%E8%99%95%E7%90%86
SUSE 10.3上裝完MYSQL
啟動時都正常,但要設定密碼時出現錯誤
SU103:/ # /etc/init.d/mysql start
Starting service MySQL done
SU103:/ # mysqladmin -u root password 'xxxxxxxx'
mysqladmin: connect to server at 'localhost' failed error: 'Access denied for user 'root'@'localhost' (using password: NO)'
處理方式如下
SU103:~ # service mysql stop
Shutting down service MySQL done
SU103:~ # clear
SU103:~ # mysqld_safe --skip-grant-tables &[1] 19984
SU103:~ # nohup: ignoring input and redirecting stderr to stdout
Starting mysqld daemon with databases from /var/lib/mysql
SU103:~ # mysql -u root mysqlWelcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.0.45 SUSE MySQL RPM
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> UPDATE user SET Password=PASSWORD('xxxxxx') where USER='root';Query OK, 3 rows affected (0.00 sec)
Rows matched: 3 Changed: 3 Warnings: 0
mysql> FLUSH PRIVILEGES;Query OK, 0 rows affected (0.00 sec)
mysql> quitBye
SU103:~ # /etc/init.d/mysql restartRestarting service MySQL
Shutting down service MySQL done
Starting service MySQL done
SU103:~ # mysql -u root -pEnter password:xxxxxxWelcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.0.45 SUSE MySQL RPM
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
打完收工~~~
啟動時都正常,但要設定密碼時出現錯誤
SU103:/ # /etc/init.d/mysql start
Starting service MySQL done
SU103:/ # mysqladmin -u root password 'xxxxxxxx'
mysqladmin: connect to server at 'localhost' failed error: 'Access denied for user 'root'@'localhost' (using password: NO)'
處理方式如下
SU103:~ # service mysql stop
Shutting down service MySQL done
SU103:~ # clear
SU103:~ # mysqld_safe --skip-grant-tables &[1] 19984
SU103:~ # nohup: ignoring input and redirecting stderr to stdout
Starting mysqld daemon with databases from /var/lib/mysql
SU103:~ # mysql -u root mysqlWelcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.0.45 SUSE MySQL RPM
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> UPDATE user SET Password=PASSWORD('xxxxxx') where USER='root';Query OK, 3 rows affected (0.00 sec)
Rows matched: 3 Changed: 3 Warnings: 0
mysql> FLUSH PRIVILEGES;Query OK, 0 rows affected (0.00 sec)
mysql> quitBye
SU103:~ # /etc/init.d/mysql restartRestarting service MySQL
Shutting down service MySQL done
Starting service MySQL done
SU103:~ # mysql -u root -pEnter password:xxxxxxWelcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.0.45 SUSE MySQL RPM
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
打完收工~~~
2014年4月29日 星期二
Using mysql in Batch Mode
http://dev.mysql.com/doc/refman/5.0/en/batch-mode.html
If you want the script to continue even if some of the statements in it produce errors, you should use the
Why use a script? Here are a few reasons:
The default output format is different (more concise) when you run
mysql in batch mode than when you use it
interactively. For example, the output of
You can also use scripts from the mysql prompt by using the
3.5 Using mysql in Batch Mode
In the previous sections, you used mysql interactively to enter queries and view the results. You can also run mysql in batch mode. To do this, put the commands you want to run in a file, then tell mysql to read its input from the file:shell> mysql < batch-file
If you are running mysql under Windows and have
some special characters in the file that cause problems, you can
do this:
C:\> mysql -e "source batch-file"
If you need to specify connection parameters on the command line,
the command might look like this:
shell>When you use mysql this way, you are creating a script file, then executing the script.mysql -hEnter password:host-uuser-p <batch-file********
If you want the script to continue even if some of the statements in it produce errors, you should use the
--force command-line option.
Why use a script? Here are a few reasons:
- If you run a query repeatedly (say, every day or every week), making it a script enables you to avoid retyping it each time you execute it.
- You can generate new queries from existing ones that are similar by copying and editing script files.
- Batch mode can also be useful while you're developing a query, particularly for multiple-line commands or multiple-statement sequences of commands. If you make a mistake, you don't have to retype everything. Just edit your script to correct the error, then tell mysql to execute it again.
-
If you have a query that produces a lot of output, you can run
the output through a pager rather than watching it scroll off
the top of your screen:
shell>
mysql <batch-file| more -
You can catch the output in a file for further processing:
shell>
mysql <batch-file> mysql.out - You can distribute your script to other people so that they can also run the commands.
- Some situations do not allow for interactive use, for example, when you run a query from a cron job. In this case, you must use batch mode.
SELECT DISTINCT
species FROM pet looks like this when
mysql is run interactively:
+---------+ | species | +---------+ | bird | | cat | | dog | | hamster | | snake | +---------+In batch mode, the output looks like this instead:
species bird cat dog hamster snakeIf you want to get the interactive output format in batch mode, use
mysql -t. To echo to the output the
commands that are executed, use mysql -vvv.
You can also use scripts from the mysql prompt by using the
source command or
\. command:
mysql>See Section 4.5.1.5, “Executing SQL Statements from a Text File”, for more information.sourcemysql>filename;\.filename
Save MySQL query results into a text or CSV file
SELECT order_id,product_name,qty
FROM orders
INTO OUTFILE '/tmp/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
2014年4月23日 星期三
MySql 里的IFNULL、NULLIF和ISNULL用法
http://www.cnblogs.com/JuneZhang/archive/2010/08/26/1809306.html
今天用到了MySql里的isnull才发现他和MSSQL里的还是有点区别,现在简单总结一下:
mysql中isnull,ifnull,nullif的用法如下:
isnull(expr) 的用法:
如expr 为null,那么isnull() 的返回值为 1,否则返回值为 0。
mysql> select isnull(1+1);
-> 0
mysql> select isnull(1/0);
-> 1
使用= 的null 值对比通常是错误的。
isnull() 函数同 is null比较操作符具有一些相同的特性。请参见有关is null 的说明。
IFNULL(expr1,expr2)的用法:
假如expr1 不为 NULL,则 IFNULL() 的返回值为 expr1;
否则其返回值为 expr2。IFNULL()的返回值是数字或是字符串,具体情况取决于其所使用的语境。
mysql> SELECT IFNULL(1,0);
-> 1
mysql> SELECT IFNULL(NULL,10);
-> 10
mysql> SELECT IFNULL(1/0,10);
-> 10
mysql> SELECT
IFNULL(1/0,'yes');
-> 'yes'
IFNULL(expr1,expr2)的默认结果值为两个表达式中更加“通用”的一个,顺序为STRING、 REAL或
INTEGER。假设一个基于表达式的表的情况, 或MySQL必须在内存储器中储存一个临时表中IFNULL()的返回值:
CREATE TABLE tmp SELECT IFNULL(1,'test') AS test;
在这个例子中,测试列的类型为 CHAR(4)。
NULLIF(expr1,expr2) 的用法:
如果expr1
= expr2 成立,那么返回值为NULL,否则返回值为 expr1。这和CASE WHEN expr1 = expr2
THEN NULL ELSE expr1 END相同。
mysql> SELECT
NULLIF(1,1);
-> NULL
mysql> SELECT NULLIF(1,2);
-> 1
如果参数不相等,则 MySQL 两次求得的值为 expr1 。
mysql中isnull,ifnull,nullif的用法如下:
isnull(expr) 的用法:
如expr 为null,那么isnull() 的返回值为 1,否则返回值为 0。
mysql> select isnull(1+1);
-> 0
mysql> select isnull(1/0);
-> 1
使用= 的null 值对比通常是错误的。
isnull() 函数同 is null比较操作符具有一些相同的特性。请参见有关is null 的说明。
IFNULL(expr1,expr2)的用法:
假如expr1 不为 NULL,则 IFNULL() 的返回值为 expr1;
否则其返回值为 expr2。IFNULL()的返回值是数字或是字符串,具体情况取决于其所使用的语境。
mysql> SELECT IFNULL(1,0);
-> 1
mysql> SELECT IFNULL(NULL,10);
-> 10
mysql> SELECT IFNULL(1/0,10);
-> 10
mysql> SELECT
IFNULL(1/0,'yes');
-> 'yes'
IFNULL(expr1,expr2)的默认结果值为两个表达式中更加“通用”的一个,顺序为STRING、 REAL或
INTEGER。假设一个基于表达式的表的情况, 或MySQL必须在内存储器中储存一个临时表中IFNULL()的返回值:
CREATE TABLE tmp SELECT IFNULL(1,'test') AS test;
在这个例子中,测试列的类型为 CHAR(4)。
NULLIF(expr1,expr2) 的用法:
如果expr1
= expr2 成立,那么返回值为NULL,否则返回值为 expr1。这和CASE WHEN expr1 = expr2
THEN NULL ELSE expr1 END相同。
mysql> SELECT
NULLIF(1,1);
-> NULL
mysql> SELECT NULLIF(1,2);
-> 1
如果参数不相等,则 MySQL 两次求得的值为 expr1 。
2014年4月20日 星期日
Mysql日期和時間函數不求人
http://fanqiang.chinaunix.net/a2/b1/20010705/150000802_b.html
| 首頁 > 數據庫 > MySQL > 正文 | ||||||
| Mysql日期和時間函數不求人 | ||||||
| 本文出自:http://linuxdb.yeah.net 作者: 晏子 (2001-07-05 15:00:00) | ||||||
|
||||||
★ 樊強制作 歡迎分享 ★
|
||||||
2014年4月17日 星期四
root 由遠端登入 MySQL 主機
http://life.iiietc.ncu.edu.tw/xms/forum/show.php?id=36503
安全性的考量,MySQL 預設安裝後,限制 root 只能從本機 127.0.0.1 的 IP 登入,若要由其他 IP 登入主機,可透過以下方式:
方法一:
開啟DOS命令視窗,切換到MySQL安裝路徑下的bin目錄:
( 例如:C:\Program Files\MySQL\MySQL Server 5.1\bin )
執行登入MySQL主機:
mysql -u root -p
登入之後執行以下的指令:
mysql>mysql> GRANT ALL PRIVILEGES ON *.* TO root@"%" IDENTIFIED BY '密碼' WITH GRANT OPTION;
P.S. *.* 表示所有的資料庫;"%"表示所有的IP都可以登入MySQL主機;密碼的部份則填入root的密碼。
若你只想在你的電腦用 root 權限登入,你可以不用 "%" 而改用你的 IP (例如:10.120.171.99) 位置,這樣就會安全一點因為除了主機和你的電腦別人仍不可以 root 登入。
方法二:
在 Server2008 的 IIS 根目錄下安裝 GUI 圖形管理程式,例如:phpMyAdmin 等程式,再透過程式來修改設定。
安全性的考量,MySQL 預設安裝後,限制 root 只能從本機 127.0.0.1 的 IP 登入,若要由其他 IP 登入主機,可透過以下方式:
方法一:
開啟DOS命令視窗,切換到MySQL安裝路徑下的bin目錄:
( 例如:C:\Program Files\MySQL\MySQL Server 5.1\bin )
執行登入MySQL主機:
mysql -u root -p
登入之後執行以下的指令:
mysql>mysql> GRANT ALL PRIVILEGES ON *.* TO root@"%" IDENTIFIED BY '密碼' WITH GRANT OPTION;
P.S. *.* 表示所有的資料庫;"%"表示所有的IP都可以登入MySQL主機;密碼的部份則填入root的密碼。
若你只想在你的電腦用 root 權限登入,你可以不用 "%" 而改用你的 IP (例如:10.120.171.99) 位置,這樣就會安全一點因為除了主機和你的電腦別人仍不可以 root 登入。
方法二:
在 Server2008 的 IIS 根目錄下安裝 GUI 圖形管理程式,例如:phpMyAdmin 等程式,再透過程式來修改設定。
訂閱:
文章 (Atom)