John Joe John Joe - 7 months ago 28
Java Question

Retrieve name in MySQL

In MySQL, there has a table named admin, with 3 columns which are adminID, name and password.

I wanted to compare the id and name from user input with the data in the MySQL. If id and password matched, display the name. However, the value of the name display is always null.

public boolean checklogin(String id, String Pass)throws Exception
{
boolean check=false;
String name = null; // because assigning null here ?
String sql = "SELECT * FROM admin WHERE adminID =? and password= ?" ;
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, id);
ps.setString(2, Pass);
ResultSet rs = ps.executeQuery();
admin lg=new admin();
lg.setID(id);
lg.setPassword(Pass);
lg.setName(name);

if(rs.next())
{
check =true;
System.out.println(lg.getName());
ps.close();
rs.close();
conn.close();
return check;
}
}


What's wrong with my code? Any help would be greatly appreciated.

Answer

It's because your not displaying the name from the database but the name you assigned which is null. You need to replace System.out.println(lg.getName()); with System.out.println(rs.getString("name"));

Comments