Create MySQL Connection in Java

0
299

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 Using Java 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.

  1. import com.mysql.jdbc.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.SQLException;
  4. import javax.swing.JOptionPane;

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

  1. Connection conn = null;
  2. public static Connection MyDbConnection(){
  3. try{
  4. String host="localhost";
  5. String db="marjohn";
  6. String user="root";
  7. String password="bebeloni";
  8. String port="3306";
  9. String path="jdbc:mysql://"+ host + ":" + port + "/" + db + "," + user + "," + password;
  10. Class.forName("com.mysql.jdbc.Driver");
  11. Connection conn= (Connection) DriverManager.getConnection(path);
  12. return conn;
  13. JOptionPane.showMessageDialog(null, e);
  14. return null;
  15. }
  16. }

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:

Facebook Comments

LEAVE A REPLY

Please enter your comment!
Please enter your name here