Connecting Java Swing Application to MySQL DB

As I said in my previous NetBeans post, here we are going to connect a Java application with MySQL database. Let’s start with a simple login form. A basic understanding of  Java Programming & MySQL is required.

Step 1: Create the GUI

You can create a very basic GUI for the login screen of your project like I have done below.

2a

Step 2: Create database

As an example what I have done here is created a database name ‘logintest’ and added a table as ‘login’ which has 3 columns ’id’, ‘username’ and ‘password’

3

Step 3: Testing MySQL Connection

After creating the database go to Services and in the Drivers section you will find the MySQL Connector option. Right click on it and click on ‘Connect Using’.

4

Step 4 : Adding MySQL connector library

In the project, you will see the ‘Libraries’ option. Right click on it, and select ‘Add Library’. You will get a list of all the libraries netbeans has. Select ‘MySQL JDBC Driver’ from the list.

5

Step 5 : Writing the code

First the submit button which will validate the login with data stored in the MySQL database. So, double click on the button and Netbeans will take you straight to the code.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jTextField1.getText().length()==0) // Checking for empty field JOptionPane.showMessageDialog(null, "Empty fields detected ! Please fill up all fields");
else if(jPasswordField1.getPassword().length==0) // Checking for empty field
JOptionPane.showMessageDialog(null, "Empty fields detected ! Please fill up all fields");
else{
String user = jTextField1.getText(); // Collecting the input
char[] pass = jPasswordField1.getPassword(); // Collecting the input
String pwd = String.copyValueOf(pass); // converting from array to string
if(validate_login(user,pwd))
JOptionPane.showMessageDialog(null, "Correct Login Credentials");
else
JOptionPane.showMessageDialog(null, "Incorrect Login Credentials");
}
}

 

 

Import following packages


import javax.swing.JOptionPane;
import java.sql.*;

 

Here I’m using a custom function to retrieve data from the database & validate the login.

private boolean validate_login(String username,String password) {
try{
Class.forName("com.mysql.jdbc.Driver"); // MySQL database connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/loginTest?" + "user=root&password=root");
PreparedStatement pst;
pst = conn.prepareStatement("Select * from login where username=? and password=?");
pst.setString(1, username);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if(rs.next())
return true;
else
return false;
}
catch(Exception e){
e.printStackTrace();
return false;
}
}

 

Step 6: Run

Now you are ready to run your login form.

6

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *