Create MySQL Connection in Java

This tutorial entitled Create MySQL Connection using Java is a part of “CRUDS” application that uses MySQL Database.

By completing this tutorial, you will understand on how to create a MySQL connection through Netbeans IDE and Java.

Before you start, download MySQL JDBC Driver library from any search engine website.

If using Netbeans IDE, this library is already bundled with the IDE.

Create MySQL Connection Steps

  1. Add/Insert a new Java Class inside your projects; we use this class for our MySQL Connection.

2. Add the MySQL JDBC Driver into your package library.

3. Above your class, insert the following codes to access the required library.

[java]import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;[/java]

4. Inside your class, insert the following codes below.

[java]Connection conn = null;
public static Connection MyDbConnection(){
String host="localhost";
String db="marjohn";
String user="root";
String password="bebeloni";
String port="3306";
String path="jdbc:mysql://"+ host + ":" + port + "/" + db + "," + user + "," + password;
Connection conn= (Connection) DriverManager.getConnection(path);
return conn;
} catch (ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(null, e);
return null;

If you have any questions or suggestion about How to Create MySQL Connection Using Java, Please feel free to contact me at our contact page.

Related Articles You May Like:

Leave a Comment