1

*In the Login page user give his username and password and logging in to the Home Page.(checking user details with MySQL database and validating data).

*In the Home page I want to show Logged As : [Logged user name] . I tried below method but not successful.

 public void showUsername() throws SQLException{



    String sql1 = "SELECT username FROM logininfo WHERE username= '"+uname+"'" ;

    stmt = conn.createStatement();
    rs = stmt.executeQuery(sql1);

    while(rs.next()){
        String name=rs.getString("username");
        loggedUname_lbl.setText("You are Logged in as : "+name);
   }

*uname is the text given by the user as the username in the Login page.

tenten
  • 1,248
  • 23
  • 50

2 Answers2

1

Try to use prepared statement and use the below query. If there is this username (uname) in table logininfo, it should be retrieved. It is always advisable to use prepared statements , it can prevent SQL Injection

How does prepared statement prevent SQL Injection

        public void showUsername() throws SQLException{

    PreparedStatement pstmt = null;

            String sql1 = "SELECT username FROM logininfo WHERE username LIKE ?" ;
  // String sql1 = "SELECT username FROM logininfo WHERE username = ?" ;
//Use above  query for an exact match 

            pstmt = conn.prepareStatement(sql1);
            pstmt.setString(1,  "%" + uname + "%");
           // pstmt.setString(1, uname); Use this for the exact match query

            rs = pstmt.executeQuery(sql1);

            while(rs.next()){
                String name=rs.getString("username");
                loggedUname_lbl.setText("You are Logged in as : "+name);
           }
        }
Community
  • 1
  • 1
Kalyan Chavali
  • 1,220
  • 7
  • 24
0

If you look at your database query, it does not make any sense. You select what you already know!

This is all you need to solve your problem:

public void showUsername() {
    loggedUname_lbl.setText("You are logged in as: " + uname);
}
Mathias Begert
  • 2,034
  • 1
  • 12
  • 26