利用shell将mysql中数据导出到文件和执行mysql语句

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_43215250/article/details/84396926
  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.
    

    示例代码

    扫描二维码关注公众号,回复: 4411816 查看本文章
    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
    

猜你喜欢

转载自blog.csdn.net/weixin_43215250/article/details/84396926