Reputation: 495
I'm using the following code to get the response from a servlet. It will check whether the given name in the variable "get" is in a particular table, and print 1
if it exists.
Portion of servlet code:
get = request.getParameter("nam");// such as get="kannan"
try {
// Connection code
ResultSet rs = stmt
.executeQuery("select * from newfarmer where rname='" + get
+ "'");
while (rs.next()) {
username = rs.getString("rname");
if (get.equals(username)) {
out.println(1);
}
}
} catch (Exception e) {
out.println(e.toString());
}
In my android application, I check this response as follows:
response = CustomHttpClient.executeHttpPost(
"http://moberp.svsugar.com:8080/androidservlt/Modify",
postParameters);
String res = response.toString();
res = res.trim();
if (res.equals("1")) {
flag = 1;
Toast.makeText(getBaseContext(), "Correct", Toast.LENGTH_LONG)
.show();
} else {
flag = 2;
Toast.makeText(getBaseContext(), "please enter correct Ryot name",
Toast.LENGTH_LONG).show();
}
It works very well for single record. I mean, in the table "newfarmer", If "rname" consists of more than one same name only the else part is executed.
Example: If "kannan" is presented 2 times in the table Servlet output is as
1 1
Now in android application, clearly the else part is executed because response is not 1. This is only case of two same names. The table may contains more than 10 same names. If 10 same names, then servlet output is as
1 1 1 1 1 1 1 1 1 1
So I need to check all. So I need to make changes in my if condition, but I don't know what to do. Someone please give answer.
Thanks in advance
Upvotes: 1
Views: 388
Reputation:
instead of while loop Use
if(rs.next())
Now it will print only one time.
No change in android
Upvotes: 2
Reputation: 15664
I don't understand why would get.equals(username)
will evaluate to false when you are having a where
clause in your SQL query?
So just try this.
if(rs.next())
{
// The above condition will make the code inside if executed
// only if any matching record is found and
//hence it will print `1` only once
//if any matching record is found.
username=rs.getString("rname");
if(get.equals(username))
{
out.println(1);
}
}
Also you are using stmt.executeQuery("select * from newfarmer where rname='"+get+"'");
which is susceptible to SQL injection.
So better use prepared statement instead.
Upvotes: 1
Reputation: 201
in servlet do this
if(rs.next())
{
username=rs.getString("rname");
if(get.equals(username))
{
out.println(1);
}
}
}
this loop will run only 1 time now if the record is present.
Upvotes: 1