Following code gives me a big headache. Why does my if ignore rs.next() == true?
System.out.println(rs.next());
if (rs.next() == true) {
System.out.println("1");
session.setAttribute("userid", userid);
//out.println("welcome " + userid);
//out.println("<a href='logout.jsp'>Log out</a>");
response.sendRedirect("success.jsp");
} else {
System.out.println("2");
out.println("Invalid password <a href='index.jsp'>try again</a>");
}
Console:
#1 SELECT * FROM users where username = 'test' and password = 'test'
#2 true
#3 2
What am I doing here wrong?
What am I doing here wrong?
You're calling next() twice. The first call returns true, but presumably the second returns false - which makes sense, if your query only returns a single result.
If you really want to print the value out for diagnostic purposes, save it in a local variable:
boolean nextResult = rs.next();
System.out.println(nextResult);
if (nextResult) {
...
} else {
...
}
Calling ResultSet#next() advances the underlying cursor. Assuming the username is really unique, if found the first call to next() will return true and advance the cursor. When the second call is made, the cursor has already exhausted all its data, so it returns false. If you want to use this value, you need to keep it instead of calling next() multiple times. E.g.:
boolean hasNext = rs.next();
System.out.println(hasNext);
if (hasNext) {
// Do stuff...
i did not get your problem exactly but first of all we should not write if statements like this
if (rs.next() == true) {
its wrong practice to check like this if(boolVar == true) it should be like this
if(boolVar){
Related
i was trying to validate my login using this code but it always shows invalid and i tried printing the value of rs variable which is true and there is no error or exception,Here is my code
String sql="SELECT * FROM user_info WHERE password=? and email_id=?";
try
{
ResultSet rs=null;
PreparedStatement ps=mycon.prepareStatement(sql);
ps.setString(1,text_eid.getText());
ps.setString(2,passwordField.getText());
rs=ps.executeQuery();
System.out.println("rs="+rs.next());
boolean b=rs.next();
if(b==true)
{
JOptionPane.showMessageDialog(null, "suc");
}
else
{
JOptionPane.showMessageDialog(null, "invalid");
}
}
catch(Exception er)
{
er.printStackTrace();
}
The problem is you are trying to print rs.next() and there may be only one result. In this case it will print true but actually assign false in variable. Remove that sysout and log the assigned variable. Except this there is nothing wrong.
As I see it, there are two problems with your code:
Your SQL string uses parameter 1 for the password and parameter 2 for the email ID:
String sql="SELECT * FROM user_info WHERE password=? and email_id=?";
// param 1--^ param 2--^
However, it seems you then proceed to pass the parameter values the other way around:
ps.setString(1,text_eid.getText());
ps.setString(2,passwordField.getText());
As pointed out elsewhere, you are calling rs.next() twice. Each time you call this method, the result set attempts to move forward one row, and the method returns whether a row was read. So the following line tries to move the result set to the first row and prints whether there was a first row:
System.out.println("rs="+rs.next());
However the next line tries to move the result set forward another row, and sets b to whether the result set has a second row:
boolean b=rs.next();
I'm guessing that in your case the result set returned one row, so you got true printed out and b was set to false.
A better way of writing this is as follows:
boolean b=rs.next();
System.out.println("rs="+b);
In this case we only call rs.next() once. Once we've got the return value of this method in b, we can then just print out b without needing to call rs.next() again.
Try this:
int result = st.executeUpdate()
if (result == 0) {
JOptionPane.showMessageDialog(null, "invalid");
} else {
JOptionPane.showMessageDialog(null, "suc");
}
or you can create a User class to set his properties like this:
User u = new User();
while (rs.next()) {
u.setId(rs.getString("email_id=?"));
}
if (u.getId() == null) {
JOptionPane.showMessageDialog(null, "invalid");
} else {
JOptionPane.showMessageDialog(null, "suc");
}
I am struggling right now to check all my InputFields wether they == "".
I found many solutions here but somehow it doesnt work.
I have a RegistrationModal and a RegistrationController.
In the modal I tryed to check the fields like that:
public boolean RegisterUser(String user, String vorname, String nachname) throws SQLException {
PreparedStatement preparedStatement = null;
if (user == "" || vorname == "" || nachname == "") {
System.out.println("Fill in all fields");
return false;
}
// Here follows the SQL query the prepared statement and exequte
}
But it it never uses this if statement, I have no idea why?
I also tryed to catch the empty element in the controller:
public void Absenden(ActionEvent event) {
try {
if (registerModel.RegisterUser(txt_user.getText(), txt_vorname.getText(),
txt_nachname.getText())) {
if (registerModel.RegisterUser(txt_user.getText().trim().isEmpty(), txt_vorname.getText().trim().isEmpty(),
txt_nachname.getText().trim().isEmpty())) {
System.out.println("False! Do something?");
}
// Here opens the new window with a notification Registration was successfull
((Node) event.getSource()).getScene().getWindow().hide();
}
Here I had errors so thats why two if statement which already seems weird, I had to autogenerate a new method in model to make this work with booleans, but still it never used this if statement.
I tryed to give only relevant code, otherwise it would be much more.
Maybe someone has an idea.
Thanks
Your condition will fail if it has one or more spaces as inputs.
You should always trim() and then check if the length is 0
i.e
user.trim().length==0
also If you want to check contents always use equals instead of ==
You should have try like this
if(use.trim.length<0)
{
// todo code !!
}
Can Anyone explain me how this code works.
// Method returns null if bitmap not available
public Bitmap getBitMap(long id) {
for ( Bitmap item : myBitmaps.keySet() ) {
if ( item != null) {
if ( item.getId() == id ) {
return item;
}
}
}
return null;
how come its possible to use two return (including one inside if block) in a function.sorry I am new to java.
Simple.
The first return statement returns the item only if the two nested conditions are satisfied.
Once your loop is over (aka the two nested conditions are not satisfied), the second return statement triggers and returns null.
In short, if your myBitmaps array or Collection contains a Bitmap that is not null and whose id equals the given id for the method, that Bitmap instance is returned.
Otherwise, null is returned.
As fge mentions, a method has to fulfill all possible return paths (save for exceptional conditions).
If null was not returned outside your loop, the code would not compile.
This would happen because if your conditions were not fulfilled, your loop would terminate without returning anything, and so would your method.
When a return statement is called the function exits. You can have multiple return statements on different places because you might want to return different values depending on what happened in the function.
At a time only one return works. When return item executes it actually returns the control to the statement line from where this method was called. In this case return null will not get execute. And when For loop executed whole and nothing happened at that time return null statement will get execute.
So at a time only one return statement will get execute, no matter if there is more than one return statements in a method.
Basically there are 3 steps:
Loop every Bitmap presents in myBitmaps
If the bitmap is 'valid' (means not null) continue. Otherwise, let's iterate to the next Bitmap.
If the id is the one you were looking at, return the Bitmap.
So what it does is: Get the Bitmap with the specified id if it exists.
the if condition should be like this:
if ( item != null && item.getId() == id){
return item;
}
I have following code
if (rs != null)
{
out.println("result set has got something");
while (rs.next())
{
//I am processing result set now
}
}
else
{
out.println("result set is empty");
}
Even though rs is null it is printing "resultset has got something". Why is it happening like that and how can I check for empty result set?
You could check it with:
if(rs != null && rs.next()) {
out.println("result set has got something");
do {
// do what you have to do
} while (rs.next());
} else {
out.println("result set is empty");
}
JDBC ResultSet objects returned as a query result are never null please read the javadoc. So the way you are checking is wrong. You can use ResultSet.next() method instead.
A ResultSet object maintains a cursor pointing to its current row of data - Unless your calling method has no guarantee the passed Resultset is generated by executing a statement via a specific query, then handling the Null Pointer using;
if(rs !=null && rs.next())
{
..
}
is essential -but if you're handling
ResultSet rs = stmt.executeQuery(..);
then no need performing Null point checking, just go straight to the point and ask ResultSet if it holds data;
String name=null;
while (rs.next())
{
name =rs.getString(1);
}
and then handle values like this;
if(name !=null && name.length()>0)
{
..
}
For record sets, its always better to use ternary operators provided by Java.
For eg:
Say you want to set the name to the user object pojo.
myUser.setName(null != recordSet.getString("name") ? recordSet.getString("name") : "Guest");
Hope this helps.
I am having a java class where I am executing a query and assigning the query result to an string array, finally return the array.
Everything works fine. But I want to return "no data" if the db values are empty (not the whole array). what can I do for this?
Code:
query="select `t1`,`t2`,`t3` from test";
PreparedStatement pre = conn.prepareStatement(query);
ResultSet res = pre.executeQuery();
String val[][] = new String[res.getRow()][3];
while (res.next()) {
val[i][0] = res.getString(1);
val[i][1] = res.getString(2);
val[i][2] = res.getString(3);
i++;
}
res.close();
conn.close();
pre.close();
return (val);
(Where I want the val[1][1] to be "No Data" if res.getString(2) is null).
No Data seems to be a value you display more than a logical value.
So you should decide of a special value and display it in a special way. We usually call this a sentry value.
This value could be null or a string that can't be in your db. (maybe it doesn't apply here as everything is often possible in a db).
Also note that it could be attractive to use an exception instead of this special value but it is actually a very poor use of exceptions, mostly for performance issues and hence it is a design to avoid if possible except if this value can lead to problems for your clients classes.
try this way
val[i][0] = (res.getString(1)!=null & !res.getString(1).equals(""))?res.getString(1).equals(""):"No Data";
val[i][1] = (res.getString(1)!=null & !res.getString(2).equals(""))?res.getString(3).equals(""):"No Data";
val[i][2] = (res.getString(1)!=null & !res.getString(3).equals(""))?res.getString(3).equals(""):"No Data";
use the only one "&" what happen when you check the condition with && first it will check for the first i.e. rs.getString(1)!=null if this is null or not it will check for the another condition i.e. rs.getString(1).equal("") so if you check and it will null then in second condition it will cause the error for NullPointerException.
while if you use only one & then it will check first condition if that was true then only it go for check the another condition otherwise not.
Add small helper methods like this:
public static String getValue(String value) {
return getValue(value, "No Data");
}
public static String getValue(String value, String default) {
return value == null ? default : value;
}
Use it like this:
val[i][0] = getValue(res.getString(1)); // standard
val[i][0] = getValue(res.getString(1), "NULL"); // with custom default message