How To Connect MySQL Database In Netbeans
Preview
Hello friends, the discussion this time is about how to make MySQL database connection using IDE NetBeans. Okay, before we need to set up the database we will connect. For example I have created a database named "dbtoko" as the image below
If the database is ready, now open Netbeans then create a new project by clicking on File menu and select New Project or can use keyboard shortcut Ctrl + Shift + N.
Then click Next and enter your project name and specify a storage location, then click Finish.
Now right click Source Package → New → Java Package.
Then name it as you see fit.
The purpose of the steps above is to create a new folder into a special folder to put the database connection file later. But this is only Optional.
The next step is to right click on the package you created and select Java Class and name it as you wish, for example I give the name ClassDB.
If it is done, now we need to enter the library named MySQL JDBC Driver as a link to our database.
By right-clicking on the package library, then select Add Libraries. Then locate the driver
Driver MySQL JDBC, then click Add Library.
MORE ARTICLE
Tutorial Login With Netbeans & MySQL
Now enter the following code in ClassDB.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class ClassDB {
private static Connection koneksi;
public static Connection getkoneksi() {
if (koneksi==null) {
try {
String url = new String();
String user = new String();
String password = new String();
url = "jdbc:mysql://localhost:3306/dbtoko";
user = "root";
password = "root";
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
koneksi = DriverManager.getConnection(url,user,password);
JOptionPane.showMessageDialog(null,"Connection Successfuly");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Connection Failed" +e);
}
}
return koneksi;
}
}
If the above code is complete and there is no error, we move the main class ie
ConnectionMySQL, then we call the function we have created earlier with the code
ClassDB.getkoneksi();
then run the project, if successful it will show a successful connection message.