i am making java app for my minor project.i am entering correct data but it not allowing to login.i am confused why the code in not working.
there are 2 fields in my database(username and pass ).i am entering correct data but it allowing me to login
`
public class login extends JFrame implements ActionListener{
JButton jb1;
JTextField tf3,tf1,tf2;
ResultSet rs;
String s2,s1,s3;
String a;
Connection con;
login(){
Container c =getContentPane();
c.setLayout(null);
c.setBackground(Color.orange);
jb1=new JButton("submit");
jb1.addActionListener(this);
jb1.setBounds(180,370,100,50);
JLabel jl1=new JLabel("username");
jl1.setBounds(10,60,100,50);
JLabel jl2=new JLabel("password");
jl2.setBounds(10,110,100,50);
JLabel jl3=new JLabel("user or emp");
jl3.setBounds(10,160,100,50);
tf1= new JTextField();
tf1.setBounds(110,70,200,40);
tf2= new JTextField();
tf2.setBounds(110,120,200,40);
tf3=new JTextField();tf3.setBounds(110,180,200,40);
tf1.setText("username");
tf2.setText("password");
c.add(tf1);c.add(tf2);c.add(tf3);
c.add(jl1);c.add(jl2);c.add(jl3);
c.add(jb1);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==jb1){
s1 = tf1.getText();
s2 = tf2.getText();
s3 = tf3.getText();
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl", "scott", "hr");
PreparedStatement ps = con.prepareStatement("select * from login ");
rs = ps.executeQuery();
while(rs.next()) {
String username = rs.getString("username");
String pass = rs.getString("pass");
if ((s1.equals(username)) && (s2.equals(pass))) {
if (s3.equals("Admin")) {
dispose();
home f=new home();
f.setSize(500,500);
f.setTitle("Bank Management System");
f.setVisible(true);
} else if (s3.equals("user")) {
dispose();
} else {
dispose();
}
} else {
JOptionPane.showMessageDialog(null, "User name and password do" + " not match!","ALERT!",JOptionPane.ERROR_MESSAGE);
break;
}
}
}
catch(Exception ex)
{
System.out.println( ex);
}
}
}
public static void main(String[] args) {
login af =new login();
af.setSize(500,500);
af.setTitle("login");
af.setVisible(true);
}
}
`
Related
I want to enter data through textfields and save them. But buttons are not working. There are no errors while I'm compiling and not even in database connection. I guess there is a logical error.
public class Database {
private static JPanel panel;
private static JLabel sname;
private static JLabel saddress;
private static JTextField t;
private static JTextField t1;
private static JButton Delete = new JButton("Delete");
private static JButton update = new JButton("Update");
private static JButton save = new JButton("Save");
private static Container c;
private static Connection con;
private static Statement st;
private static ResultSet rs;
Database() {
connect();
}
public void connect(){
try{
System.out.println("Entered");
System.out.println("Database connection started...");
con=DriverManager.getConnection("jdbc:ucanaccess://D:\\test.mdb");
System.out.println("Hello satarted");
st = con.createStatement();
System.out.println("Connection ok.");
while(rs.next())
{
System.out.println(rs.getString("Student Name"));
System.out.println(rs.getString("Student Address"));
System.out.println();
}
catch (SQLException e){
System.err.println("Exception: " + e.getMessage());
}
}
public static void main(String[] args) {
Database gui = new Database();
JFrame f = new JFrame();
f.setTitle("School Management System");
f.setSize(300, 200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sname = new JLabel("Student Name");
t = new JTextField(10);
saddress = new JLabel("Student Address");
t1 = new JTextField(10);
panel = new JPanel();
panel.add(sname);
panel.add(t);
panel.add(saddress);
panel.add(t1);
// panel.add(insert);
panel.add(Delete);
panel.add(update);
panel.add(save);
f.add(panel);
try {
rs.next();
t.setText(rs.getString("Student Name"));
t1.setText(rs.getString("Student Address"));
} catch (Exception ex) {
}
}
public void btnAction() {
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = t.getText();
String address = t1.getText();
try {
rs.moveToInsertRow();
rs.updateString("Student Name", name);
rs.updateString("Student Address", address);
rs.insertRow();
rs.close();
} catch (Exception ex) {
}
}
});
update.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String sname = t.getText();
String saddress = t1.getText();
try {
rs.updateString("Student name", sname);
rs.updateString("Student address", saddress);
rs.updateRow();
JOptionPane.showMessageDialog(null, "Record Updated!");
} catch (Exception e) {
}
}
});
}
}
when i removed static from each of these variables. I got so many errors
Yes, any time you see a class full of static variables you know the class is designed incorrectly.
Start with the working example from the Swing tutorial on How to Use Text Field. Download the TextDemo code and understand how it works and then make the changes for your logic.
Note how the class extends a JPanel where all the variables and components are defined and there is no need for any static variable. Your code should look something like this.
Once you have a better designed class you can then start to debug your code to figure out why the SQL isn't working.
Here is my MS SQL DB
Here is my Java Connection
I have used SQL Server Authentication Login: sa Password: root
Database is loaded, but I can not pass login. Probably can not read a table but I don't know why.
Here is my Login Class
JLabel lbUsername = new JLabel("Username: ");
JLabel lbPassword = new JLabel("Password: ");
JTextField tfUsername = new JTextField(20);
JPasswordField tfPassword = new JPasswordField(20);
JButton btnLogin = new JButton("Uloguj se");
String loginQuery = "SELECT USERNAME, PASSWORD FROM RADNIK";
boolean ulogovan;
public Login() {
setLayout(new MigLayout("fill"));
setTitle("Logovanje");
setSize(250, 150);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel login = new JPanel(new MigLayout("insets 10"));
login.add(lbUsername);
login.add(tfUsername, "wrap");
login.add(lbPassword);
login.add(tfPassword, "wrap");
add(login, "dock north, grow");
JPanel button = new JPanel(new MigLayout("insets 10"));
button.add(btnLogin, "align center");
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!tfUsername.getText().equals("")
&& !tfPassword.getPassword().equals("")) {
String username = tfUsername.getText();
String password = "";
for (char ch : tfPassword.getPassword()) {
password += ch;
}
try {
ulogovan = logIn(loginQuery, username, password);
if (ulogovan == true) {
MainFrame main = new MainFrame();
main.setVisible(true);
} else {
JOptionPane
.showMessageDialog(
null,
"Uneli ste neispravno korisnicko ime ili lozinku!",
"Obavestenje",
JOptionPane.WARNING_MESSAGE);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null,
"Molimo vas popunite sve podatke!", "Obavestenje",
JOptionPane.INFORMATION_MESSAGE);
}
}
});
add(button, "dock south, grow");
}
public boolean logIn(String sql, String username, String password)
throws SQLException {
ArrayList<String> radnici = new ArrayList<String>();
Statement stmt = DBConnection.getConnection().createStatement();
ResultSet rset = stmt.executeQuery(sql);
while (rset.next()) {
String usernameTemp = rset.getString("USERNAME");
String passwordTemp = rset.getString("PASSWORD");
radnici.add(usernameTemp);
radnici.add(passwordTemp);
}
if (radnici.contains(username) && radnici.contains(password)) {
return true;
}
return false;
}
Any suggestion?
I've set up a Gui and a JBDC. I have listed in my tables a username : admin and password : admin and when I input these into the gui login it is still locking me out and im unsure why its locking me out... Below is my code
public class Login extends JFrame {
private JTextField jtfUsername, jtfPassword;
private JButton backButton, loginButton;
private JMenuItem jmiLogin, jmiBack, jmiHelp, jmiAbout;
Login() {
//create menu bar
JMenuBar jmb = new JMenuBar();
//set menu bar to the applet
setJMenuBar(jmb);
//add menu "operation" to menu bar
JMenu optionsMenu = new JMenu("Options");
optionsMenu.setMnemonic('O');
jmb.add(optionsMenu);
//add menu "help"
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
helpMenu.add(jmiAbout = new JMenuItem("About", 'A'));
jmb.add(helpMenu);
//add menu items with mnemonics to menu "options"
optionsMenu.add(jmiLogin = new JMenuItem("Login", 'L'));
optionsMenu.addSeparator();
optionsMenu.add(jmiBack = new JMenuItem("Back", 'B'));
//panel p1 to holds text fields
JPanel p1 = new JPanel(new GridLayout(2, 2));
p1.add(new JLabel("Username"));
p1.add(jtfUsername = new JTextField(15));
p1.add(new JLabel("Password"));
p1.add(jtfPassword = new JPasswordField(15));
//panel p2 to holds buttons
JPanel p2 = new JPanel(new FlowLayout());
p2.add(backButton = new JButton("Back"));
p2.add(loginButton = new JButton("Login"));
//Panel with image??????
//add panels to frame
JPanel panel = new JPanel(new GridLayout(2, 1));
panel.add(p1, BorderLayout.CENTER);
panel.add(p2, BorderLayout.SOUTH);
add(panel, BorderLayout.CENTER);
setTitle("Main Page");
//listners for exit menuitem and button
jmiBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Welcome welcome = new Welcome();
welcome.setVisible(true);
welcome.setSize(500, 500);
welcome.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
Login.this.dispose();
Login.this.setVisible(false);
}
});
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Welcome welcome = new Welcome();
welcome.setVisible(true);
welcome.setSize(500, 500);
welcome.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
Login.this.dispose();
Login.this.setVisible(false);
}
});
//listner for about menuitem
jmiAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"This is the login panel"
+ "\n Assignment for University",
"About", JOptionPane.INFORMATION_MESSAGE);
}
});
//action listeners for Login in button and menu item
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
boolean loggedIn = usernamecheck.checkLogin(jtfUsername.getText(), jtfPassword.getText());
if (!loggedIn) {
JOptionPane.showMessageDialog(null,"Sorry, wrong credentials");
//displayErrorMessage("Sorry, wrong credentials");
return;
}
}
catch (SQLException se) {
se.printStackTrace();
JOptionPane.showMessageDialog(null,
"Sorry, couldn't check your credentials. Check the logs and report the problem to an administrator.");
return;
}
MainMenu mainmenu = new MainMenu();
mainmenu.setVisible(true);
mainmenu.setSize(500, 500);
mainmenu.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
Login.this.dispose();
Login.this.setVisible(false);
}
});
jmiLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainMenu mainmenu = new MainMenu();
mainmenu.setVisible(true);
mainmenu.setSize(500, 500);
mainmenu.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
Login.this.dispose();
Login.this.setVisible(false);
}
});
}
public static void main(String arg[]) {
Login frame = new Login();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class usernamecheck {
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database";
static final String USERNAME = "root";
static final String PASSWORD = "root";
// launch the application
public static boolean checkLogin(String username, String password)
throws SQLException {
System.out.print("Running Check Login \n");
Connection connection = null; // manages connection
PreparedStatement pt = null; // manages prepared statement
Statement stmt = null;
String query="select userName from person where userName = ? and password = ?";
// connect to database usernames and query database
try {
// establish connection to database
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(DATABASE_URL, "root", "root");
// query database
pt = con.prepareStatement("select userName from person where userName = ? and password = ?");
// process query results
pt.setString(1, username);
ResultSet rs = pt.executeQuery(query);
String orgUname = "", orPass = "";
if (rs.next()) {
orgUname = rs.getString("userName");
orPass = rs.getString("password");
} //end while
if (rs.next() && password.equals(rs.getString("password")) && username.equals(rs.getString("userName"))) {
//do something
return true;
} else {
//do something
return false;
}
}//end try
catch (Exception e) {
} //end catch
return false;
} //end main
}
In your checkLogin(String username, String password) method,
you set username for PreparedStatement as parameter but you forgot to set password
// query database
pt = con.prepareStatement("select userName from person where userName = ? and password = ?");
// process query results
pt.setString(1, username);
??
Trying to set up a JDBC that checks a database for a matching username and password, and they when the login button is pressed if matching the user is granted access, I've got my current code here, but I'm unsure what is missing when I launch the program it seems like its not checking the database for the correct information.
Updated:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class NewClass extends JFrame {
private JTextField jtfUsername, jtfPassword;
private JButton backButton, loginButton;
private JMenuItem jmiLogin, jmiBack, jmiHelp, jmiAbout;
NewClass() {
//create menu bar
JMenuBar jmb = new JMenuBar();
//set menu bar to the applet
setJMenuBar(jmb);
//add menu "operation" to menu bar
JMenu optionsMenu = new JMenu("Options");
optionsMenu.setMnemonic('O');
jmb.add(optionsMenu);
//add menu "help"
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
helpMenu.add(jmiAbout = new JMenuItem("About", 'A'));
jmb.add(helpMenu);
//add menu items with mnemonics to menu "options"
optionsMenu.add(jmiLogin = new JMenuItem("Login", 'L'));
optionsMenu.addSeparator();
optionsMenu.add(jmiBack = new JMenuItem("Back", 'B'));
//panel p1 to holds text fields
JPanel p1 = new JPanel(new GridLayout(2, 2));
p1.add(new JLabel("Username"));
p1.add(jtfUsername = new JTextField(15));
p1.add(new JLabel("Password"));
p1.add(jtfPassword = new JPasswordField(15));
//panel p2 to holds buttons
JPanel p2 = new JPanel(new FlowLayout());
p2.add(backButton = new JButton("Back"));
p2.add(loginButton = new JButton("Login"));
//Panel with image??????
//add panels to frame
JPanel panel = new JPanel(new GridLayout(2, 1));
panel.add(p1, BorderLayout.CENTER);
panel.add(p2, BorderLayout.SOUTH);
add(panel, BorderLayout.CENTER);
setTitle("Main Page");
//listners for exit menuitem and button
jmiBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Welcome welcome = new Welcome();
welcome.setVisible(true);
welcome.setSize(500, 500);
welcome.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Welcome welcome = new Welcome();
welcome.setVisible(true);
welcome.setSize(500, 500);
welcome.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
//listner for about menuitem
jmiAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"This is the login panel"
+ "\n Assignment for University",
"About", JOptionPane.INFORMATION_MESSAGE);
}
});
//action listeners for Login in button and menu item
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
usernamecheck.checkLogin(jtfUsername.getText(), jtfPassword.getText()); {
System.out.println("User is validated");
}
} catch (SQLException se) {
}
MainMenu mainmenu = new MainMenu();
mainmenu.setVisible(true);
mainmenu.setSize(500, 500);
mainmenu.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
jmiLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainMenu mainmenu = new MainMenu();
mainmenu.setVisible(true);
mainmenu.setSize(500, 500);
mainmenu.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
}
public static void main(String arg[]) {
log frame = new log();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class usernamecheck {
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/test";
static final String USERNAME = "root";
static final String PASSWORD = "root";
// launch the application
public static boolean checkLogin(String username, String password)
throws SQLException {
System.out.print("dfdF");
Connection connection = null; // manages connection
PreparedStatement pt = null; // manages prepared statement
// connect to database usernames and query database
try {
// establish connection to database
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(DATABASE_URL, "root", "root");
// query database
pt = con.prepareStatement("select userName,password from test.person where userName=?");
// process query results
pt.setString(1, username);
ResultSet rs = pt.executeQuery();
String orgUname = "", orPass = "";
while (rs.next()) {
orgUname = rs.getString("userName");
orPass = rs.getString("password");
} //end while
if (orPass.equals(password)) {
//do something
return true;
} else {
//do something
}
}//end try
catch (Exception e) {
} //end catch
return false;
} //end main
}
Make your checkLogin method return boolean type and return true inside if (orPass.equals(password)) { block. Check whether the method true if so grant access.
You are missing a return type in your checkLogin method. You may return a boolean value to validate the user. Also add some logging/sysout to make sure what is happening in your code.
Update your method as :
// launch the application
public static boolean checkLogin(String username, String password)
throws SQLException {
System.out.print("dfdF");
Connection connection = null; // manages connection
PreparedStatement pt = null; // manages prepared statement
// connect to database usernames and query database
try {
// establish connection to database
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(DATABASE_URL, "root", "root");
// query database
pt = con.prepareStatement("select userName,password from test.person where userName=?");
// process query results
pt.setString(1, username);
ResultSet rs = pt.executeQuery();
String orgUname = "", orPass = "";
while (rs.next()) {
orgUname = rs.getString("userName");
orPass = rs.getString("password");
} //end while
if (orPass.equals(password)) {
//do something
return true;
rs.close();
} else {
//do something
}
}//end try
catch (Exception e) {
} //end catch
return false;
} //end main
And then update your user check as
try {
if(usernamecheck.checkLogin(jtfUsername.getText(), jtfPassword.getText())) {
System.out.println("User is validated");
} else {
return;
}
} catch (SQLException se) {
}
I'm trying to make a authorization JFrame to MS Access DB, but query does'nt seems to wirk properly. The idea is to intup login and password, and if one of them isn't correct, get a message. My code always sends me to the exception. Here is my code, maybe someone can help me.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class First {
JFrame frame;
JPanel txt, but;
JButton log, ext;
JTextField login;
JLabel l, p;
JPasswordField pass;
PreparedStatement prepst;
ResultSet res;
public First() {
frame = new JFrame("Authorization");
txt = new JPanel();
but = new JPanel();
log = new JButton("Login");
ext = new JButton("Quit");
login = new JTextField(10);
l = new JLabel("Login:");
p = new JLabel("Password:");
pass = new JPasswordField(10);
frame.setSize(400,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txt.add(l);
txt.add(login);
txt.add(p);
txt.add(pass);
frame.add(txt,BorderLayout.NORTH);
but.add(log);
but.add(ext);
frame.add(but,BorderLayout.SOUTH);
log.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evnt) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String PathToDataBase = "D:/workspace2/MicrosoftAccessConnection/db";
String DataBase = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
DataBase += PathToDataBase.trim() + ";DriverID=22;READONLY=true}";
Connection con = DriverManager.getConnection(DataBase,"","");
prepst = con.prepareStatement("SELECT * FROM USERS WHERE LOGIN= AND PASSWORD=?");
String lll = login.getText();
String ppp = pass.getText();
prepst.setString(1,lll);
prepst.setString(2, ppp);
res = prepst.executeQuery();
if((test(con,lll,ppp)) == true) {
while(res.next()) {
if((lll.equals(res.getString("LOGIN"))) && (ppp.equals(res.getString("PASSWORD")))) {
lol();
} else {
JOptionPane.showMessageDialog(null, "Wrong data");
}
}
}
res.close();
prepst.close();
con.close();
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "Error with connection");
}
}
});
ext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evnt) {
frame.dispose();
}
});
frame.setVisible(true);
}
public void lol() {
JFrame f = new JFrame("SUCCESS");
f.setSize(200,200);
frame.dispose();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
boolean test(Connection con, String login, String pass) throws SQLException {
int rez = 0;
PreparedStatement st = con.prepareStatement("SELECT COUNT(*) FROM USERS WHERE LOGIN=? AND PASSWORD=?");
st.setString(1, login);
st.setString(2, pass);
ResultSet res = st.executeQuery();
while (res.next()) {
rez = res.getInt(1);
}
st.close();
return rez == 1;
}
public static void main(String[] args) {
new First();
}
}
You're missing a PreparedStatement placeholder character from your SQL, replace
SELECT * FROM USERS WHERE LOGIN= AND PASSWORD=?
with
SELECT * FROM USERS WHERE LOGIN=? AND PASSWORD=?
^
If you're getting an Exception, its always best to display the exception content. You could add this to the exception block:
e.printStackTrace();