开发者

Query to a MySQL database from shell

I need to make several queries to MySql database. My question is the following:

  1. Do I add the following in a file and then execute the file:

echo "Check "

mysql -h 192.168.100.1 -t -u u开发者_运维知识库mane -pass tablename < query.sql

echo "Check "

mysql -h 192.168.100.1 -t -u umane -pass tablename < query2.sql

echo "Check "

mysql -h 192.168.100.1 -t -u umane -pass tablename < query3.sql

echo "Check "

mysql -h 192.168.100.1 -t -u umane -pass tablename < query4.sql

  1. Or I create a single "query.sql" file that contains all the sql querys. If so, can I in any way echo the "Check" statments somehow?


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


You could create one sql file and then add some SELECT statements like this

// 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";

The result of this looks like

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     |
+-------------+

-- edit, yeah the same as Dimitre's suggestion


Put all your sql statements in source.sql and you redirect the output into output.txt

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


You can add text (and timestamp) selects in the SQL code:

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

So your single SQL file would look like:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜