How to use SQL in terminal?
I want to create simple tables, insert values in it, and do queries. How to perform them in the terminal?
Here is the syntax to execute sql statement from terminal
I'm assuming that you are using MySQL
.
Syntax:
mysql -u user_name -p password -e 'SQL Query' database
Clearificance:
-u : Specify mysql database user name
-p : Prompt for password
-e : Execute sql query
database : Specify database name
Example:
-
If you want to create a table
person
then:mysql -u root -p -e 'Create table person(PersonID int, LastName varchar(255), FirstName varchar(255))' mydb
where
root
is the username,mydb
is the name of the database. Similary you can execute any query you want. -
If you want to
insert
values inperson
:mysql -u root -p -e 'Insert into person(PersonID,LastName,FirstName) Values(100,"Kumar","Saurav")' mydb
-
If you want to select all the information from
person
and want to save in a file:mysql -u root -p -e 'Select * from person' mydb > personinfo
And of-course you can create a database using terminal itself
-
To create database mydb execute following command in terminal:
mysql -u root -p -e 'create database mydb'
it will silently create a database mydb without giving any message/output.
-
To list all the databases execute this command in terminal:
mysql -u root -p -e 'show databases'
Hope it helps you.. Reply if you need further assistance..
You make a database by typing
mysql
In the prompt you enter, you then start by creating your database (as explained by onik in the comments):
CREATE DATABASE dbname
Once you have made that database, you can experiment with it. You can simply type mysql
in a terminal and you can get do anything sql related you want. It is possible that you have create to a role in your database with your username.
As described in Sauruv's answer you can also connect to the database as follows (without the space between p and your password or better, just do not use the -p option and you will get a password prompt [credits go to onik]):
Syntax:
mysql -u user_name -ppassword dbname
-u : Specify mysql database user name
-p : Prompt for password
dbname : Specify database name