'Connection to MySQL from a JFrame

I want to connect to MySQL using a JFrame but the program is telling me "error while establishing connection"

This is what I tried:

These are the declaration I did before writing the code below:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

This is the code I use for the connection:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
   String un= user.getText();
   String p= pass.getText();
    
   try{
       Class.forName("com.mysql.jdbc.Driver");
            Connection conn= (Connection) DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/sms","root","");
            Statement st= (Statement)conn.createStatement();
            String sql= "select * from user_login";
             
             ResultSet rs= st.executeQuery(sql);
             while(rs.next()){
                  String username= rs.getString("username");
                  String Password= rs.getString("password");
           if(un.equals(username) && p.equals(Password)){
                    new welcome().setVisible(true);
        }
            else
        {
            JOptionPane.showMessageDialog(this, "Username or Password is incorrect!");
        }
             }
           
       } 
   catch(Exception e){
        JOptionPane.showMessageDialog(null, "Error while establishing connection");
    }

Expecting to be connected using this code but the program is telling me "error while establishing connection"



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source