Click here to Skip to main content
15,884,537 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey I have this bit of code that is suppose to return true if the there is a student that already has this sutdentID and false in the other case. However the rowcount is always 0 and therefore the code always return false. The SQL statment seems to work, I've tested it on the database it self. Here is the code:

Java
String sql = ("SELECT * FROM std_details WHERE StudentID='"+id+"';");
		int rowCount = 0;
		ResultSet rs;
		try {
			rs = stmt.executeQuery(sql);
			while ( rs.next() )  
			{  
			    rowCount++;  
			}  
			System.out.println(rowCount);
		} catch (SQLException e1) {
			e1.printStackTrace();
		}

		if (rowCount > 0){
			return true;
		}else{
			return false;
		}
Posted
Updated 18-Dec-14 22:38pm
v2
Comments
Shweta N Mishra 19-Dec-14 5:22am    
code seems to be correct, Did you have passed correct studentId in parameter ?
Member 11322545 19-Dec-14 5:37am    
yea, I did I don't understand anymore :/

1 solution

Change the code as follows:

C#
String sql = ("SELECT Count(*) as found FROM std_details WHERE StudentID='"+id+"';");
        int rowCount = 0;
        try {
rs = stmt.executeQuery(sql);
rs.next();  
rowCount = rs.getInt(1);
            System.out.println(rowCount);
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
            return (rowCount > 0);
    }
 
Share this answer
 
v2
Comments
Member 11322545 19-Dec-14 6:06am    
there is a compilation error on executeScalar, says i sould use execute instead, and I did think of using exists but i've been stuck on this function for a while so i decided to go the easy way. Finally I did not design the database, it does make sense indeed to have the id as an int.
Sinisa Hajnal 19-Dec-14 6:11am    
Execute scalar: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v=vs.110%29.aspx

Which database are you using?
Member 11322545 19-Dec-14 6:12am    
MySQL InnoDB and I'm using java
Sinisa Hajnal 19-Dec-14 6:18am    
Solution updated for java...it should be database agnostic...it works because count(*) always returns a value.
Richard MacCutchan 19-Dec-14 6:29am    
You should not use (or encourage others to use) string concatenation in SQL. Use proper parameterised queries.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900