前言線上下做mysql資料分析的時候,會遇到執行shell指令碼裡匯入sql檔案到mysql資料庫裡或者串連mysql執行指定sql語句的情況,這裡介紹一下我採用的方法匯入sql檔案到mysql資料庫
範例程式碼
#變數定義sqlname="test.sql"dir="/sdb2/backup/mysql_db_backup/backup/databases"host="127.0.0.1"user="root"passwd="123456"dbname="test"#匯入sql檔案到指定資料庫mysql -h$host -u$user -p$passwd $dbname < $dir/$sqlname
關鍵點"<"運算子的使用執行指定的sql語句mysql的-e參數參數解釋
--execute=statement, -e statementExecute the statement and quit. The default output format is like that produced with --batch
--silent, -sSilent mode. Produce less output. This option can be given multiple times to produce less and less output.
範例程式碼
select_sql="select count(distinct id) from tb_test"num=$(mysql -s -h$host -u$user -p$passwd $dbname -e "$register_sql")
注意:
- -s參數的使用是減少查詢欄位的輸出(ps:我這裡只需要查詢的結果值,並不需要查詢的欄位名,不加-s參數會輸出查詢的欄位名)
管道運算子
echo "select count(distinct id) from tb_test" | mysql -h$host -u$user -p$passwd $dbname
ps:我建議使用-e參數,更加方便吧
mysqldump匯出mysql資料匯出指定條件的資料庫
命令格式
mysqldump -u使用者名稱 -p密碼 -h主機 資料庫名 表名 --where "sql語句"> 路徑
範例程式碼
#!/bin/bash#變數定義host="127.0.0.1"user="root"passwd="123456"dbname="test"tablename="tb_test"mysqldump -u$user -p$passwd -h$host $dbname $tablename --where "id > 1 and id < 1000" > 1.sql
匯出一個資料結構(無資料)參數
--no-data, -dDo not write any table row information (that is, do not dump table contents). This is useful if you want to dump only the CREATE TABLE statement for the table (for example, to create an empty copy of the table by loading the dump file).
命令格式
mysqldump -u使用者名稱 -p密碼 -h主機 資料庫名 -d > 路徑
範例程式碼
#!/bin/bash#變數定義host="127.0.0.1"user="root"passwd="123456"dbname="test"mysqldump -u$user -p$passwd -h$host $dbname -d > 2.sql
參考連結http://blog.linezing.com/2012/02/mysql%E5%AF%BC%E5%85%A5%E5%AF%BC%E5%87%BA%E6%95%B0%E6%8D%AE%E6%96%B9%E6%B3%95