Pages

Ads 468x60px

Saturday, October 18, 2014

Java: Connection with MySQL using JDBC


This will help you create connection with MySQL database using Java (JDBC). You have to update database URL, username and password in the code, then run it you will get connection established as output.  Please include mysql-connector-java-5.1.23-bin.jar in your project build path. You can download it from here: http://www.java2s.com/Code/JarDownload/mysql/mysql-connector-java-5.1.23-bin.jar.zip



import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {

public static void main(String[] args){
getConnection();
}

    public static Connection getConnection(){
    Connection conn = null;
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost/database_name";
            String user = "root";
            String password = "";
            conn =  DriverManager.getConnection(url, user, password);
            System.out.println("Connection established");
        }
        catch(ClassNotFoundException e)
        {
            System.out.println(e.getMessage());
            System.exit(0);
        }
        catch(SQLException e)
        {
            System.out.println(e.getMessage());
            System.exit(0);
        }
        return conn;
    }
}

No comments:

Post a Comment