9

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.

2 Answers 2

13
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       |                |
+------------------+------------------+------+-----+---------+----------------+
Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

I like that I can echo the command right into MySQL. That was helpful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.