从shell查询MySQL数据库

时间:2011-09-29 12:18:54

标签: mysql shell

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

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

    echo“Check”
    mysql -h 192.168.100.1 -t -u umane -pass tablename   < query.sql
    echo“检查”
    mysql -h 192.168.100.1 -t -u umane   -pass tablename< query2.sql
    echo“检查”
    mysql -h   192.168.100.1 -t -u umane -pass tablename< query3.sql
    echo   “检查”
    mysql -h 192.168.100.1 -t -u umane -pass tablename<   query4.sql

    1. 或者我创建一个包含所有sql查询的“query.sql”文件。如果是这样,我能否以某种方式回应“检查”的陈述?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

您可以创建一个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的建议一样

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

您可以在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...