1. 程式人生 > >MySQL資料庫分庫分表指令碼實現

MySQL資料庫分庫分表指令碼實現

目錄

1 MySQL分庫指令碼實現

vim /server/scripts/mysqldump.sh
#!/bin/bash

USER=root
PASSWORD=123456
SOCKET=/data/3306/mysql.sock
LOGIN="mysql -u$USER -p$PASSWORD -S $SOCKET"
DUMP="mysqldump -u$USER -p$PASSWORD -S $SOCKET"
DATABASE=$($LOGIN -e "show databases;"|egrep -v "*schema$|mysql"|sed '1d')

for database in
$DATABASE do $DUMP $database| gzip >/server/backup/${database}_$(date +%F).sql.gz done

測試

[[email protected] ~]# bash /server/scripts/mysqldump.sh
[[email protected] ~]# cd /server/backup/
[[email protected] backup]# ll
total 20
-rw-r--r-- 1 root root 871 Jun 11 10:08 oldboy_2018-06-11.sql.gz
-rw-r--r-- 1 root root 450 Jun 11 10:08 oldgirl_2018-06-11.sql.gz -rw-r--r-- 1 root root 450 Jun 11 10:08 rsq123_2018-06-11.sql.gz -rw-r--r-- 1 root root 447 Jun 11 10:08 rsq_2018-06-11.sql.gz -rw-r--r-- 1 root root 727 Jun 11 10:08 rsq_utf8_2018-06-11.sql.gz

2 MySQL分表指令碼實現

vim /server/scripts/mysqldump1.sh
#!/bin/bash
USER=root PASSWORD=123456 SOCKET=/data/3306/mysql.sock LOGIN="mysql -u$USER -p$PASSWORD -S $SOCKET" DUMP="mysqldump -u$USER -p$PASSWORD -S $SOCKET" DATABASE=$($LOGIN -e "show databases;"|egrep -v "*schema$|mysql"|sed '1d') for database in $DATABASE do TABLE=$($LOGIN -e "use $database; show tables;"|sed '1d') for table in $TABLE do if [ -d /server/backup/$database ];then $DUMP $database $table | gzip >/server/backup/$database/${database}_${table}_$(date +%F).sql.gz else mkdir /server/backup/$database -p $DUMP $database $table | gzip >/server/backup/$database/${database}_${table}_$(date +%F).sql.gz fi done done

測試

[[email protected] ~]# bash /server/scripts/mysqldump1.sh
[[email protected] ~]# cd /server/backup/
[[email protected] backup]# ll
total 8
drwxr-xr-x 2 root root 4096 Jun 11 10:00 oldboy
drwxr-xr-x 2 root root 4096 Jun 11 10:00 rsq_utf8
[[email protected] backup]# tree
.
├── oldboy
│   ├── oldboy_student_2018-06-11.sql.gz
│   └── oldboy_test_2018-06-11.sql.gz
└── rsq_utf8
    └── rsq_utf8_rsq_2018-06-11.sql.gz

2 directories, 3 files
[[email protected] backup]# cd
[[email protected] ~]# mysql -uroot -p123456 -S /data/3306/mysql.sock -e "show databases;"
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| oldboy             |
| oldgirl            |
| performance_schema |
| rsq                |
| rsq123             |
| rsq_utf8           |
+--------------------+

# 為什麼這麼多資料庫卻只有兩個資料庫目錄生成,原因是其它資料庫都是空的
[[email protected] ~]# mysql -uroot -p123456 -S /data/3306/mysql.sock -e "use rsq;show tables;"
[[email protected] ~]# mysql -uroot -p123456 -S /data/3306/mysql.sock -e "use rsq123;show tables;"
[[email protected] ~]# mysql -uroot -p123456 -S /data/3306/mysql.sock -e "use rsq_utf8;show tables;"
+--------------------+
| Tables_in_rsq_utf8 |
+--------------------+
| rsq                |
+--------------------+