1. 程式人生 > >利用shell將mysql中資料匯出到檔案和執行mysql語句

利用shell將mysql中資料匯出到檔案和執行mysql語句

  1. 利用mysqldump匯出mysql資料

    匯出指定條件的資料庫
    命令格式

    mysqldump -u使用者名稱 -p密碼 -h主機 -P埠 資料庫名 表名  --where "sql語句" > 路徑
    

    示例程式碼

    #!/bin/bash
    #變數定義
    host="127.0.0.1"
    port="3306"
    user="root"
    passwd="123456"
    dbname="test"
    tablename="tb_test"
    mysqldump -u$user -p$passwd -h$host -P${port} $dbname $tablename --where "id > 1 and id < 1000"
    > ${tablename}.sql
  2. 匯入sql檔案到mysql資料庫

    匯出sql檔案到資料庫
    命令格式

    mysql -h主機 -P埠 -u使用者名稱 -p密碼 資料庫名 < 路徑/檔案
    

    示例程式碼

    #!/bin/bash
    #變數定義
    sqlname="test.sql"
    dir="/sdb2/backup/mysql_db_backup/backup/databases"
    host="127.0.0.1"
    port="3306"
    user="root"
    passwd="123456"
    dbname="test"
    
    #匯入sql檔案到指定資料庫
    mysql -h$host -P${port}
    -u$user -p$passwd $dbname < $dir/$sqlname

    關鍵點
    "<"運算子的使用

  3. shell執行指定的sql語句

    mysql的-e引數

    引數解釋

    --execute=statement, -e statement
    Execute the statement and quit. The default output format is like that produced with --batch
    --silent, -s
    Silent 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")
    echo $num       
    

    輸出結果:

    1. 加 -s 輸出count(distinct f_Uid) 8721
    2. 不加 -s 輸出 8721

    注意:
    -s引數的使用是減少查詢欄位的輸出(ps:我這裡只需要查詢的結果值,並不需要查詢的欄位 名,不加-s引數會輸出查詢的欄位名)

    管道運算子

    echo "select count(distinct id) from tb_test" | mysql -h$host -u$user -p$passwd $dbname
    
  4. 匯出一個數據結構(無資料)
    引數

    --no-data, -d
    Do 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主機 -P埠 資料庫名 -d > 路徑
    

    示例程式碼

    #!/bin/bash
    #變數定義
    host="127.0.0.1"
    port="3306"
    user="root"
    passwd="123456"
    dbname="test"
     
    mysqldump -u$user -p$passwd -h$host -P${port} $dbname -d > 2.sql