這幾天作一個任務,比對兩個數據表中的數據,今天寫個shell版本的,這樣,在全部linux系列機器上就均可以運行了。mysql
shell操做mysql其實就是經過mysql命令經過參數去執行語句,跟其餘程序裏面是同樣的,看看下面這個參數:linux
-e, --execute=name Execute command and quit. (Disables --force and history file.)
所以咱們能夠經過mysql -e來執行語句,就像下面這樣:sql
mysql -hlocalhost -P3306 -uroot -p123456 $test --default-character-set=utf8 -e "select * from users"
執行以後返回下面結果:
shell
MYSQL="mysql -h192.168.1.102 -uroot -p123456 --default-character-set=utf8 -A -N" #這裏面有兩個參數,-A、-N,-A的含義是不去預讀所有數據表信息,這樣能夠解決在數據表不少的時候卡死的問題 #-N,很簡單,Don't write column names in results,獲取的數據信息省去列名稱 sql="select * from test.user" result="$($MYSQL -e "$sql")" dump_data=./data.user.txt >$dump_data echo -e "$result" > $dump_data #這裏要額外注意,echo -e "$result" > $dump_data的時候必定要加上雙引號,不讓導出的數據會擠在一行 #下面是返回的測試數據 3 吳彥祖 32 5 王力宏 32 6 ab 32 7 黃曉明 33 8 anonymous 32
#先看看要導入的數據格式,三列,分別是id,名字,年齡(數據是隨便捏造的),放入data.user.txt 12 tf 23 13 米勒 24 14 西安電子科技大學 90 15 西安交大 90 16 北京大學 90 #OLF_IFS=$IFS #IFS="," #臨時設置默認分隔符爲逗號 cat data.user.txt | while read id name age do sql="insert into test.user(id, name, age) values(${id}, '${name}', ${age});" $MYSQL -e "$sql" done
輸出結果數據庫
+----+--------------------------+-----+ | id | name | age | +----+--------------------------+-----+ | 12 | tf | 23 | | 13 | 米勒 | 24 | | 14 | 西安電子科技大學 | 90 | | 15 | 西安交大 | 90 | | 16 | 北京大學 | 90 | +----+--------------------------+-----+
#先看看更新數據的格式,將左邊一列替換爲右邊一列,只有左邊一列的刪除,下面數據放入update.user.txt tf twoFile 西安電子科技大學 西軍電 西安交大 西安交通大學 北京大學 cat update.user.txt | while read src dst do if [ ! -z "${src}" -a ! -z "${dst}" ] then sql="update test.user set name='${dst}' where name='${src}'" fi if [ ! -z "${src}" -a -z "${dst}" ] then sql="delete from test.user where name='${src}'" fi $MYSQL -e "$sql" done
輸出結果:測試
+----+--------------------------+-----+ | id | name | age | +----+--------------------------+-----+ | 12 | twoFile | 23 | | 13 | 米勒 | 24 | | 14 | 西軍電 | 90 | | 15 | 西安交通大學 | 90 | +----+--------------------------+-----+
#利用mysqldump這個命令能夠很輕鬆的導出全部數據的sql語句到指定文件 #導出root@localhost下面的exp.Opes中的全部數據到tt.sql mysqldump -h localhost -u root -p exp Opes > ./tt.sql #回車以後輸入密碼就能夠將全部sql語句輸出到tt.sql
#設置編碼,否則可能出現亂碼 mysql -hlocalhost -uroot --default-character-set=gbk -p exp< ./tt.sql #回車以後輸入密碼,導入tt.sql中的全部數據到exp數據庫中