Database Connecting Program
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class dbConnect {
Connection conn = null;
String host = "jdbc:mysql://localhost:3306/";
String dbName = "cse1";
String username = "root";
String password = "vamsi";
String driver = "com.mysql.jdbc.Driver";
Connection con;
PreparedStatement pst;
ResultSet rs;
dbConnect()
{
try{
Class.forName(driver);
con = DriverManager.getConnection(host + dbName, username, password);
pst = con.prepareStatement("SELECT * FROM login WHERE uname = ? and pwd = ?");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public Boolean vertify(String uname, String pwd)
{
try{
pst.setString(1, uname); //this replace the 1st "?" in the query for username
pst.setString(2, pwd); //this replace the 2nd "?" in the query for password
//execute the prepared statement
rs = pst.executeQuery();
if(rs.next())
{
//TRUE iff query founds any corresponding data
return true;
}
else
{
return false;
}
}catch (Exception e)
{
//TODO Auto-generate catch block
System.out.println("error while validating" + e);
return false;
}
}
}
_______________________________________________________________________________
Graphical User Interface
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class logInMenu1{
Frame frame1 = new Frame("Log-in Form");
Button SUBMIT;
Label lUsername, lPassword;
TextField username, password;
dbConnect dbC=new dbConnect();
public logInMenu1()
{
createAndShowGUI();
}
void login()
{
lUsername = new Label("Username");
username = new TextField(15);
lPassword = new Label("Password");
password = new TextField(15);
SUBMIT = new Button("SUBMIT");
Panel panel = new Panel(new GridLayout(3,1));
panel.setSize(200,50);
panel.add(lUsername);
panel.add(username);
panel.add(lPassword);
panel.add(password);
panel.add(SUBMIT);
frame1.add(panel, BorderLayout.CENTER);
SUBMIT.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String uname = username.getText();
String pwd = password.getText();
System.out.println("value1: " + uname);
System.out.println("value2: " + pwd);
if(dbC.vertify(uname, pwd))
{
//a pop-up box
JOptionPane.showMessageDialog(null, "You have logged in successfully", "Success",
JOptionPane.INFORMATION_MESSAGE);
}
else
{
//a pop-up box
JOptionPane.showMessageDialog(null, "Login failed!", "Failed!",
JOptionPane.INFORMATION_MESSAGE);
}
}
});
}
void createAndShowGUI(){
frame1.setSize(400, 150);
frame1.setVisible(true);
frame1.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
login();
}
public static void main(String[] args)
{
new logInMenu1();
}
}