【问题标题】:Query to a MySQL database from shell从 shell 查询 MySQL 数据库
【发布时间】:2012-11-13 17:39:07
【问题描述】:

我需要对 MySql 数据库进行多次查询。我的问题如下:

  1. 我是否在文件中添加以下内容,然后执行该文件:

echo "检查"
mysql -h 192.168.100.1 -t -u umane -pass 表名 echo "检查"
mysql -h 192.168.100.1 -t -u umane -pass 表名 echo "检查 "
mysql -h 192.168.100.1 -t -u umane -pass 表名 回显 “检查”
mysql -h 192.168.100.1 -t -u umane -pass 表名

  1. 或者我创建一个包含所有 sql 查询的“query.sql”文件。如果是这样,我可以以某种方式呼应“检查”语句吗?

【问题讨论】:

    标签: mysql shell


    【解决方案1】:
    username="my_sql username"
    password="my_sql password"
    result=`mysql -h 192.168.100.1  --port=$port -u $username --password=$password -e 'select * from database.table_name'`
    
    echo $result
    

    【讨论】:

      【解决方案2】:

      你可以创建一个 sql 文件,然后像这样添加一些 SELECT 语句

      // Does not print anyting
      CREATE TABLE test (col1 int, col2 varchar(2)); 
      // Prints a non-existing table with 1 column and 1 row
      SELECT "CHECK 1" AS "Test result"; 
      // This does prints some output
      DESCRIBE test;
      // Prints the check 'table' again
      SELECT "CHECK 2" AS "Test result";
      

      这个结果看起来像

      my@server:~$ mysql -t -u root databasename < sqltest 
      +-------------+
      | Test result |
      +-------------+
      | CHECK 1     |
      +-------------+
      +-------+------------+------+-----+---------+-------+
      | Field | Type       | Null | Key | Default | Extra |
      +-------+------------+------+-----+---------+-------+
      | col1  | int(11)    | YES  |     | NULL    |       |
      | col2  | varchar(2) | YES  |     | NULL    |       |
      +-------+------------+------+-----+---------+-------+
      +-------------+
      | Test result |
      +-------------+
      | CHECK 2     |
      +-------------+
      

      -- 编辑,是的,与 Dimitre 的建议相同

      【讨论】:

        【解决方案3】:

        将所有 sql 语句放在 source.sql 中,然后将输出重定向到 output.txt

        mysql -t -uuserid -ppassword -hhostname < source.sql > output.txt
        

        【讨论】:

          【解决方案4】:

          您可以在 SQL 代码中添加文本(和时间戳)选择:

          % mysql -NBe "select now(); select 'check'; select now();select 'check'"
          2011-09-29 14:46:15
          check
          2011-09-29 14:46:15
          check
          

          所以你的单个 SQL 文件看起来像:

          --- queries from sql1...
          SELECT NOW()
          SELECT 'check';
          -- queries from sql2...
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2014-03-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-03-16
            • 1970-01-01
            相关资源
            最近更新 更多