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.
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");
}
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){
I am having an issue in getting the data in the below loop ,even though the size is not zero i am getting null in the sysout 'data is'.What is wrong there ?
List<Long> dd = domainItemMapper.getIsSearchable(34372);
System.out.println("the test is-" + dd.size());
for (int i = 0; i < dd.size(); i++) {
Long isSearch = dd.get(i);
System.out.println("data is"+dd.get(i));
if (isSearch.equals(0)) {
isSearchValue = false;
} else
isSearchValue = true;
}
The call to database is a mybatis call as below
interface
List<Long> getIsSearchable(#Param("parentFieldId") long parentFieldId);
impl
<mapper namespace="com.ge.dbt.common.persistence.IFormValidatorMapper">
<select id="getIsSearchable" statementType="CALLABLE"
resultType="Long">
select is_searchable from t_field where parent_field_id=#{parentFieldId}
</select>
</mapper>
I guess your whole code can be converted in to two lines.
if(dd!= null && !dd.isEmpty())
return dd.contains(0);//Contains Guard you in such cases because equals check
//happen on passed element ie *0*
Default value of Long in java is null. So you will need additional check for null in your case.
Enclose your isSearch.equals check in a null check
if(isSearch != null)
{
if (isSearch.equals(0))
{
isSearchValue = false;
}
else
{
isSearchValue = true;
}
}
However it'll be better to modify code for domainItemMapper.getIsSearchable(34372); method so that it doesn't fill the list with null at all.
Seems to be your list contains null literals. And List Supports null as a value.
based on your this comment
The data has null,0 and 1 data.I want to return data only for 0 and 1.
You need to fix your query like this
select is_searchable from t_field where parent_field_id=#{parentFieldId} and is_searchable is not NULL;
Assuming I have two methods. One that creates an arraylist and returns it, the other retrieving that list to process. both methods are in different classes:
public ArrayList getSocialUsers() throws SQLException
{
Connection conn=DriverManager.getConnection("jdbc:mysql:///socialsystemtest1?user=root&password=");
Statement stmt= null;
String query="SELECT FORE_NAME FROM socialsystemtest1.socialworkers";
stmt= conn.createStatement();
ArrayList<String> socialWorkers= new ArrayList<String>();
try{
ResultSet rs= stmt.executeQuery(query);
while(rs.next())
{
String user= rs.getString("Fore_Name");
socialWorkers.add(user);
}
}
catch(SQLException e) {
//do nothing
}
finally{
if(stmt != null) {
stmt.close();
}
}
return socialWorkers;
}
public void processArray(){
try{
ArrayList<String>= db.getSocialUsers();
//code ommitted
}
catch(SQLException e){
//deal with it here
}
}
db is an instance of the class that returns the arraylist already instantiated. I recieve a null pointer error at the first line of the second classes method: db.getSocialUsers();
when calling the getSocialUsers() method on its own this works and an ArrayList is indeed returned with the correct elements but when calling it from another class gives a null pointer and I don't know why
This means that the db object is null, not the ArrayList. Where are you instantiating it?
Edit: I recommend you replace the instantiation in the constructor with a member initialization:
public class Admin {
Database db = new Database();
// etc.
}
If a line
ArrayList<String> array = db.getSocialUsers();
causes a NullPointerException, this can only be a result of db being null. You should check if the database is opened and the reference is stored in db
make ArrayList<String> socialWorkers a field in the first class. Check that your db object is not null.
In your second class where you have processArray how are you initializing db. As per your post it seems that db is null hence it throws NPE.
Make sure you have initialized db
Your code in processArray should be like this:
ArrayList<String> valuesFromDB = db.getSocialUsers();
Though better programming will always ask you to do like this :
List<String> valuesFromDB = db.getSocialUsers();
And your getSocialUsers should return List instead of ArrayList like:
public List<String> getSocialUsers() throws SQLException
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