shell指令碼中匯入mysql資料&&執行mysql語句

來源:互聯網
上載者:User
前言線上下做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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.