Reputation: 11
heres my code :
code for connecting database :
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=city_mart;user=sa;password=aptech");
Statement st=con.createStatement();
String sql="Select Emp_login_ID from employee where Emp_login_ID = '"+r3.getText()+"' ";
ResultSet rs=st.executeQuery(sql);
String login = rs.getString(1);
if (r3.getText().equalsIgnoreCase(login))
{
JOptionPane.showMessageDialog(rootPane, "Login ID not available.");
}
else
{
JOptionPane.showMessageDialog(rootPane, "Login ID is available.");
}
thanks.any help is much appreciated.
Upvotes: 1
Views: 5187
Reputation: 46841
You have forgotten to call ResultSet#next()
before calling ResultSet#getString()
First move the cursor at the the first row then get value of any column.
I suggest you to use PreparedStatment
instead of Statement
.
Read tutorial on Using Prepared Statements and When we use PreparedStatement instead of Statement?
It should be like this: (check the value returned by rs.next())
String sql="Select Emp_login_ID from employee where Emp_login_ID = ?";
PreparedStatement st = con.prepareStatement(sql);
st.setString(1,r3.getText());
ResultSet rs=st.executeQuery(sql);
if(rs.next()){
String login = rs.getString(1);
JOptionPane.showMessageDialog(rootPane, "Login ID is available.");
}else{
JOptionPane.showMessageDialog(rootPane, "Login ID not available.");
}
Upvotes: 2
Reputation: 310957
It will throw an exception because you have failed to call ResultSet.next()
. If you had called it, it would have returned false
, and you shouldn't have called rs.getString()
at all.
Upvotes: 0
Reputation: 59
You can try :
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=city_mart;user=sa;password=aptech");
Statement st=con.createStatement();
String sql="Select Emp_login_ID from employee where Emp_login_ID = '"+r3.getText()+"' ";
ResultSet rs=st.executeQuery(sql);
while(rs.next()){
String login = rs.getString(1);
if (r3.getText().equalsIgnoreCase(login))
{
JOptionPane.showMessageDialog(rootPane, "Login ID not available.");
}
else
{
JOptionPane.showMessageDialog(rootPane, "Login ID is available.");
}
}
Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
You can read about Next method of Result Set here
Upvotes: 0