shell处理mysql增、删、改、查
生活随笔
收集整理的這篇文章主要介紹了
shell处理mysql增、删、改、查
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
shell處理mysql增、刪、改、查
引言
????這幾天做一個任務(wù),比對兩個數(shù)據(jù)表中的數(shù)據(jù),昨天用PHP寫了一個版本,但考慮到有的機(jī)器沒有php或者php沒有編譯mysql擴(kuò)展,就無法使用mysql系列的函數(shù),腳本就無效了,今天寫個shell版本的,這樣,在所有l(wèi)inux系列機(jī)器上就都可以運(yùn)行了。
shell是如何操作mysql的?
????shell操作mysql其實(shí)就是通過mysql命令通過參數(shù)去執(zhí)行語句,跟其他程序里面是一樣的,看看下面這個參數(shù):
-e, --execute=name Execute command and quit. (Disables --force and history file.)因此我們可以通過mysql -e來執(zhí)行語句,就像下面這樣:
mysql -hlocalhost -P3306 -uroot -p123456 $test --default-character-set=utf8 -e "select * from users"執(zhí)行之后返回下面結(jié)果:
在shell腳本中操作mysql
導(dǎo)出數(shù)據(jù)
MYSQL="mysql -h192.168.1.102 -uroot -p123456 --default-character-set=utf8 -A -N" #這里面有兩個參數(shù),-A、-N,-A的含義是不去預(yù)讀全部數(shù)據(jù)表信息,這樣可以解決在數(shù)據(jù)表很多的時候卡死的問題 #-N,很簡單,Don't write column names in results,獲取的數(shù)據(jù)信息省去列名稱 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的時候一定要加上雙引號,不讓導(dǎo)出的數(shù)據(jù)會擠在一行 #下面是返回的測試數(shù)據(jù) 3 吳彥祖 32 5 王力宏 32 6 ab 32 7 黃曉明 33 8 anonymous 32插入數(shù)據(jù)
#先看看要導(dǎo)入的數(shù)據(jù)格式,三列,分別是id,名字,年齡(數(shù)據(jù)是隨便捏造的),放入data.user.txt 12 tf 23 13 米勒 24 14 西安電子科技大學(xué) 90 15 西安交大 90 16 北京大學(xué) 90 #OLF_IFS=$IFS #IFS="," #臨時設(shè)置默認(rèn)分隔符為逗號 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輸出結(jié)果
+----+--------------------------+-----+ | id | name | age | +----+--------------------------+-----+ | 12 | tf | 23 | | 13 | 米勒 | 24 | | 14 | 西安電子科技大學(xué) | 90 | | 15 | 西安交大 | 90 | | 16 | 北京大學(xué) | 90 | +----+--------------------------+-----+更新數(shù)據(jù)
#先看看更新數(shù)據(jù)的格式,將左邊一列替換為右邊一列,只有左邊一列的刪除,下面數(shù)據(jù)放入update.user.txt tf twoFile 西安電子科技大學(xué) 西軍電 西安交大 西安交通大學(xué) 北京大學(xué)cat update.user.txt | while read src dst doif [ ! -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輸出結(jié)果:
+----+--------------------------+-----+ | id | name | age | +----+--------------------------+-----+ | 12 | twoFile | 23 | | 13 | 米勒 | 24 | | 14 | 西軍電 | 90 | | 15 | 西安交通大學(xué) | 90 | +----+--------------------------+-----+本文版權(quán)歸作者iforever[]所有,未經(jīng)作者本人同意禁止任何形式的轉(zhuǎn)載,轉(zhuǎn)載文章之后必須在文章頁面明顯位置給出作者和原文連接。
本文轉(zhuǎn)自:http://www.cnblogs.com/iforever/p/4459857.html
轉(zhuǎn)載于:https://www.cnblogs.com/Rozdy/p/4468045.html
總結(jié)
以上是生活随笔為你收集整理的shell处理mysql增、删、改、查的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#, CLR, and .NET Fr
- 下一篇: 5.1 四则运算