Stole
Stole

Reputation: 5308

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 umane -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?

Upvotes: 0

Views: 3057

Answers (4)

Dimitre Radoulov
Dimitre Radoulov

Reputation: 28000

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

Upvotes: 0

Milind
Milind

Reputation: 11

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

Upvotes: 1

Joost
Joost

Reputation: 3209

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

Upvotes: 1

Aman Agarwal
Aman Agarwal

Reputation: 755

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

Upvotes: 1

Related Questions