Java JDBC Log in Form
15,785
Solution 1
Use getPassword() instead of getText()
method.
char []passChars=passwordField.getPassword();
if(passChars!=null) {
String pass=new String(passChars);
String sql="SELECT employee_ID,employee_password FROM user
where user=? and employee_password=?";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1,user);
ps.setString(2,pass);
ResultSet rs=ps.executeQuery();
if(rs.next()) {
//found
}
else{
//not found
}
rs.close();
ps.close();
conn.close();
}
One thing worth noting is that don't use hard-coded sql statement. Use PreparedStatement
to escape string to prevent SQL injection.
Solution 2
char[] p = passField.getPassword();
String password = new String(p);
I think you should use PreparedStatement
PreparedStatement prepstmt = con
.prepareStatement("SELECT employee_ID,employee_password FROM user where username = ? AND Password = ? ");
prepstmt.setString(1, user);
prepstmt.setString(2, password);
ResultSet rs;
rs = prepstmt.executeQuery();
boolean found = rs.next();
if (found)
System.out.println(rs.getString(1));
prepstmt.close();
}
Author by
user962206
Updated on June 17, 2022Comments
-
user962206 almost 2 years
I can't seem to get the password and user name on my Java JTextfield and Passwordfield, what I was trying to do is compare user input and check them if the username and password is stored in the database, if so they will be logged in, but the problem is my getText() on my password field is deprecated how would I fix this??
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.*; import javax.swing.JOptionPane; public class Login extends JFrame { private JLabel nameLabel; private JLabel passwordLabel; private JTextField nameText; private JPasswordField passwordField; private JButton submitButton; Connection conn = null; public Login(){ super("Log in!"); setLayout(new FlowLayout()); setVisible(true); setSize(178,190); setDefaultCloseOperation(EXIT_ON_CLOSE); nameLabel = new JLabel("User ID: "); add(nameLabel); nameText = new JTextField(10); add(nameText); passwordLabel = new JLabel("Password: "); add(passwordLabel); passwordField = new JPasswordField(10); add(passwordField); submitButton = new JButton("Submit"); add(submitButton); ButtonHandler handler = new ButtonHandler(); submitButton.addActionListener(handler); } private class ButtonHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ String user = nameText.getText(); String pass = passwordField.getText(); try{ Jdbc test = new Jdbc(); conn = test.dbConn(); String query = "SELECT employee_ID,employee_password FROM user where ='"+user+"'"; }catch(Exception eee){ eee.printStackTrace(); } } } }