简体   繁体   中英

Login with SQL authentication in Java

I'm trying to build a login UI with Java. But there is a problem with my SQL authentication

Here's the code:

    public void actionPerformed(ActionEvent e){
            if (e.getSource() == Login)

                    try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                Connection con=DriverManager.getConnection("jdbc:odbc:MessageStore","sa","12345"); 
                Statement cmd=con.createStatement(); 
                ResultSet rs=cmd.executeQuery("select * from UserList where UserName='"+nameText.getText());
    }

But there is a warning with "rs": The value of the local variable rs is not used

How to solve this problem?

Or is there more straightforward code to implement SQL authentication?

Thank you

In most cases of "The value of variable X is not used" you can choose to ignore the message or remove the assignment to it. In those cases you do nothing with the value.

In this case however, you only perform a query on the database, but never do anything with the result. So you don't know if the user you are trying to validate is indeed a valid user.

So, you must use the variable "rs" to check if there is indeed a result and the user is allowed to login.

public void actionPerformed(ActionEvent e){
  if (e.getSource() == Login){
    try {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // may not be needed since JDBC4
      Connection con=DriverManager.getConnection("jdbc:odbc:MessageStore","sa","12345"); 
      PrePareStatement cmd=con.prepareStatement("select * from UserList where username=?"); // safer, protect against 
      cmd.setString(1,nameText.getText());
      ResultSet rs=cmd.executeQuery();
      if( rs.next() ){
        // username does exist, now check the password
      }else{
        // username does not exist
      }
    }catch(Exception e){}
  }
}

Make ResultSet as global variable.

public void actionPerformed(ActionEvent ae) {
if (ae.getSource() != null) {
String connectionUrl = "jdbc:sqlserver://localhost:1420;" + "databaseName=TestsampleDB1;";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("Driver okay");
    con = (Connection) DriverManager.getConnection("jdbc:odbc:MessageStore", "sa", "12345");
    System.out.println("Connection Made");
    PreparedStatement cmd = con.prepareStatement("select * from UserList where username=?");

    if (rs.next()) {
        // login user exist
    } else {
    // user doesn't exist}
    }
} catch (Exception e) {
    e.printStackTrace();
  }

} }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM