MySql Database connection code in Java



import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
 *
 * @author Sudhanshu
 */
public class DBCon {
    private static Connection con;
    private final static String userName="yourusername";
    private final static String password="yourpassword";
    private final static String host="localhost";
    private final static String port="3306";
    private final static String dbName="yourdatabasename";
    private final static String driver="com.mysql.jdbc.Driver";
    private final static String url="jdbc:mysql://"+host+":"+port+"/"+dbName;
   
    static{
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException ex) {
            System.out.println(ex);
        }
      
    }
   
    public static Connection getConnection() throws SQLException{
   
            if((con==null)||(con.isClosed())){
                con=DriverManager.getConnection(url, userName, password);
            }
      
        return con;
    }
}
 

You can get the connection reference of database using the following code statement:

Connection con= DBCon.getConnection();