How to run mysql command from terminal?
I have the following sql command which I usually run in phpmyadmin by selecting the database, then running it in the command window.
DELETE FROM `wp_posts` WHERE `post_type` = "attachment"However I've never done this via terminal before. My question is, how do I "point" this command to a specific database and then run it?
47 Answers
For you to run it from terminal, you need to be logged into mysql first and then you execute your program. The ideal code would be
mysql -u(username) -p(password) (the name of the database) -e "DELETE FROM `wp_posts` WHERE `post_type` = "attachment""I`m sure this works, hope it helps
2I think you have forgot your user name for mySQL. so please enter the correct user name and password when you type mysql command. for eg
$ mysql -u root -p
Enter Password:Note: Default user name and password is root
Just type the following command in terminal to use mysql interpreter:
mysql -u root -p database_name
Enter your password, then you can run your mysql commands.
Another way is to use:
mysql -u root -p database_name << eof DELETE FROM `wp_posts` WHERE `post_type` = "attachment" eof
Try this:
mysql --host *HOST_IP* --user *USER* --password=*PASSWORD* -D *DATABASE_NAME* -e "DELETE FROM `wp_posts` WHERE `post_type` = "attachment" ; Using the MySQL CLI client.
$ mysql -u <user> -p
mysql> use <your-database>
mysql> DELETE FROM `wp_posts` WHERE `post_type` = "attachment"Notice that I'm using -u and username, but in -p I'm not setting anything. MySQL will ask you for your password.
And if you're trying to use it inline, you can use
$ mysql -u <user> -p <your-database> -e "DELETE FROM `wp_posts` WHERE `post_type` = 'attachment'"Here, notice that I'm using also -e argument. It stands for execute.
Pro tip
In MySQL client you can use:
mysql> show databases;if you want to view all dabatases in your server. And you can use:
mysql> use <database>;
mysql> show tables;if you want to view all tables into a database.
I'm using $ and mysql> as prompts, $ means your Linux terminal, and mysql>, MySQL client.
There is a series of steps to Execute MySQL in Linux Ubuntu Terminal.
- Execute MySQL Client using the following command:
mysql -u root -p - It is important to Create a New Database first using the command:
create database demo_db; - Then you have to Authorize the Database using the command:
grant all on demo_db.* to ‘testuser’ identified by ‘12345’; - Then Log in from the Database itself using the command:
mysql -u testuser -p - Then, you can actually start with the actual SQL Commands.
I referred to the article where they have explained perfect steps to Execute MySQL in Linux Ubuntu! Hope I got your MySQL Running Perfectly.
1Okay basically it was "SELECT databasename;" then executing my command.
1