joh-3
joh-3

Reputation:

Command line: log in to MySQL and execute command in one line

I often find the need to check a table structure (to check column names for instance when writing a PHP script). My one single purpose is: speed. I use "Adminer" and in a few clicks I can check it out. But I want to do this faster, with a command line window I have always open anyway. So I'd like to create a function that allows me to do something like:

mysql -uuser -ppassword && USE database; && DESCRIBE table;

I would alias this in a way that I can call:

describe database.table

And voilá, I get the database structure. But my issue is: how can I log into MySQL AND run certain queries in one script?? I have not found a way to do this.

Upvotes: 9

Views: 9258

Answers (2)

Ike Walker
Ike Walker

Reputation: 65527

mysql database -uuser -ppassword -e "describe table;"

For example:

mysql -uuser -ppassword mysql -e "describe time_zone;"
+------------------+------------------+------+-----+---------+----------------+
| Field            | Type             | Null | Key | Default | Extra          |
+------------------+------------------+------+-----+---------+----------------+
| Time_zone_id     | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| Use_leap_seconds | enum('Y','N')    | NO   |     | N       |                |
+------------------+------------------+------+-----+---------+----------------+

If you're looking for a way to alias this in your shell, you can use a function, like this:

function describe() { mysql -uuser -ppassword $1 -e "describe $2;"; }
describe mysql time_zone
+------------------+------------------+------+-----+---------+----------------+
| Field            | Type             | Null | Key | Default | Extra          |
+------------------+------------------+------+-----+---------+----------------+
| Time_zone_id     | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| Use_leap_seconds | enum('Y','N')    | NO   |     | N       |                |
+------------------+------------------+------+-----+---------+----------------+

Upvotes: 13

Michael Berkowski
Michael Berkowski

Reputation: 270599

Just an alternative method - rather than the -e flag, you can pipe in your query. useful if the query is generated by some other process:

echo "DESCRIBE table;" | mysql -uuser -ppassword databasename

Or if you have a bunch of statements listed in a file like:

# File: statements.sql
DESCRIBE table;
SELECT col FROM table;

You can instruct mysql to read from the file:

mysql -uuser -ppassword databasename < statements.sql

Upvotes: 3

Related Questions