Article updated on

Quick MySql Commands and Examples

Here is a list of my most frecently used MySql Commands and examples

Login to MySQL console

mysql -u root -pmypassword

mysql -h[] -u root -pmypassword


Send SQL statement without login to the DataBase

mysql -u root -pmypassword mydb -e "select now()"


Create/ Drop the DataBase

mysqladmin -u root -pmypassword drop mydb
mysqladmin -u root -pmypassword create mydb


Export/Import a DataBase

mysqldump -u root -pmypassword --quick mydb | gzip > myzipfile.gz
gunzip < myzipfile.gz | mysql -u root -pmypassword mydb

If lock error use:
mysqldump --single-transaction -u user -p DBNAME > backup.sql
mysql -u root -p DBNAME < backup.sql


Export/Import a DataBase Table

mysqldump -u root -pmypassword --quick mydb mytable
gunzip < myzipfile.gz | mysql -u root -pmypassword mydb


Information Squema

select * from information_schema.columns
where table_schema = 'your_db'
order by table_name, ordinal_position;

SELECT * FROM information_schema.processlist WHERE TIME > 5;


Give permissions to the DataBase

grant all privileges on mydb.* to myuser@'%' identified by 'mypasswd';
grant all privileges on mydb.* to myuser@localhost identified by 'mypasswd';


Create linked tables with a Foreign key

    category VARCHAR(100) NOT NULL,
        PRIMARY KEY (id)
    lang VARCHAR(2) NOT NULL,
    url VARCHAR(100) NOT NULL,
    meta_keywords VARCHAR(100) NOT NULL,
    title VARCHAR(120) NOT NULL,
    meta_description VARCHAR(100) NOT NULL,
    intro VARCHAR(500) NOT NULL,
    status VARCHAR(1) NOT NULL,
    last_update date NOT NULL,
    id_categories INT NOT NULL,
        PRIMARY KEY (id),
        FOREIGN KEY (id_categories) REFERENCES CATEGORIES(id)


Check if the database is listening for new connections.

  •  Linux example change port accordingly: sudo netstat -anltp|grep :3306 or sudo nmap -p 3306 localhost
  • Windows your database port should be among the ones listed: netstat -an


* The port should be listening if not the problems is that the database installation is wrong or is blocked by a firewall.

Test Code Snippet

import java.sql.*;
public class Connect {
    private static final long PAUSE_MILLIS = 70000;
    public static void main(String[] args) {
        Connection conn = null;
        try {
            String userName = "root";
            String password = "mypassword";//change accordingly
            String url = "jdbc:mysql://localhost:3306";//change accordingly
            conn = DriverManager.getConnection(url, userName, password);
            PreparedStatement ps1;
            System.out.println("Database connection established");            
                try {
                    ps1 = conn
                            .prepareStatement("SELECT CURRENT_TIMESTAMP() as Date");
                    ResultSet rs = ps1.executeQuery();
                    while ( {
                } catch (SQLException e) {
                System.out.println("Wating for next iteration...");
        } catch (Exception e) {
            System.err.println("Cannot connect to database server");
        } finally {
            if (conn != null) {
                try {
                    System.out.println("Database Connection Terminated");
                } catch (Exception e) {


* Change the URL, PORT, PASSWORD, PAUSE_MILLIS accordingly


Telnet Data Base

Using telnet can be very use full to find out if you can reach the database. ex. in console type telnet youdatabaseip port. or  telnet youdatabaseip:port if you are using windows. If telnet is not installed in your windows google windows install telnet. search install telnet

Press Intro twice if you are getting this means that your database can receive connections.


Try different combinations such us.

  • telnet localhost 3306
  • telnet 3306
  • telnet 3306
  • telnet 3306

* Change accordingly to your local network ip, external IP and database port.

* With this you can determine whether it is a network-related problem or not.


MySql Configuration files

  • Linux MySQL ex: /etc/my.cnf
  • Windows ex: MySQL: C:\Program Files\mysql\bin\my.ini
  • Comment out or Change "bind-address" attribute and change it to Ips: bind-address="" or bind-address=""
  • Comment out "skip-networking"

* If you are getting the exception every now than then perhaps adding the following properties will help you.

  • wait_timeout = number
  • interactive_timeout = number
  • connect_timeout = number


 MySQL TimeOut 

  • Log to your MySQL Console Linux ex. mysql -u root -pmypassword
  • From the MySQL Console show the time variables show global variables like '%time%' 


* The wait time out is in seconds and will close the the opened connections. You can update in the configuration files #configfiles or ex. for ten minutes  set global wait_timeout=600;


Show active connections

  • In MySQL console show full processlist; or show full processlist\G; or SELECT host,count(host) FROM information_schema.processlist GROUP BY host;


* The amount of open connections and traffic can shutdown the database.

  • Info shows the MySQL command being run
  • use kill id_process to remove processes.


Pool Tomcat examples

Pool with validation query, 2 maxIdle connections

        <Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource"
        driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/blog"
        username="root" password="mypasswd" maxActive="10" maxIdle="2" validationQuery="SELECT 1"/>


Pool with no idle connections that removes all the unclosed connections

        <Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource"
        driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/blog"
        username="root" password="mypasswd" maxActive="10" maxIdle="2" maxWait="45" 
        maxAge="45" removeAbandoned="true" removeAbandonedTimeout="45"/>


JSP For Testing Purposes Only.

<%@ page language="java" contentType="text/html; charset=UTF-8"
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="javax.naming.Context" %>
<%@ page import="javax.naming.InitialContext" %>
<%@ page import="javax.naming.NamingException" %>
<%@ page import="javax.sql.DataSource" %>    
Context context = new InitialContext();
DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/mysql");
    Connection con = ds.getConnection();
    PreparedStatement ps1 = con
            .prepareStatement("SELECT CURRENT_TIMESTAMP() as Date");
    ResultSet rs = ps1.executeQuery();
    while ( {
        out.println("Date From DataBase " +rs.getString("Date"));