No return data from PreparedStatement query - java

I am trying to do a SELECT using PreparedStatement, but not getting any results back, despite the data being present. If I use Statement instead, I get the desired results, so not sure why I don't get anything with the PreparedStatement.
Any ideas?
Here is my code:
String species = "Snail";
PreparedStatement preparedStatement = con.prepareStatement("Select * from lifeforms where species=?",PreparedStatement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, species);
preparedStatement.execute();
ResultSet resultSet = preparedStatement.getGeneratedKeys();
Also - I have tried just
resultSet = preparedStatement.execute();
But this won't compile, saying I must change resultSet to expect a boolean value.
Any insights into this would be greatly appreciated.
Sorry if this is something obvious, but I have read the docs until I am almost unconscious, and I'm only just learning java.

The execute() functon returns a boolean value so u won't be able to put this in an object of resultset, if you want to execute a select statement you have to use executeQuery().

Ah so I have finally found the answer to this question - in case anyone else is stuck on the same thing..
The execute() method has no return value, although the compiler was suggesting it expected a boolean return value. Maybe it just returns true or false for successful or not?
The executeUpdate() method returns an int value of the number of records updated/inserted or deleted.
To get the result set of a query statement (e.g. Select * from someTable), use the
ResultSet rs = preparedStatement.executeQuery() method.
This will return the actual query results into a ResultSet variable.

Related

Getting resultset twice from statement

I understand that using statement.getResultSet() returns the result set as well as statement.executeQuery() but what happens if both are used like executeQuery() is called first and then getResultSet() is called after does it work or will it throw an exception that the result set has already been returned?
Please look into this
executeQuery: Returns one ResultSet object.
ResultSet rs = stmt.executeQuery(query);

Getting Incorrect return in java accessing sql database

This is the code im using in java to query the database
connect = DriverManager.getConnection (url, "user", "pass");
state = connect.createStatement();
String meetID = "SELECT GamerTag FROM backup";
ResultSet rs = state.executeQuery(meetID);
while(rs.next()){
System.out.println(rs.toString());
}
Im not getting the values of the row in the database im getting this instead
com.mysql.jdbc.JDBC4ResultSet#108137c9
You're printing the result of the toString method of the Recordset object, which appears to print out the object's name and hashcode.
Instead, try to print the value of a column. Perhaps using getString:
System.out.println(rs.getString("GamerTag"));
The documentation for Java's recordset looks confusing, you might be better off searching for examples.
What do you expect rs.toString() should do it will just print the hash of the resultsetObject if you want to get the column values you should do this way
while(rs.next()){
System.out.println(rs.getString("yourFirstColumnName")+" "+
rs.getString("yourSecondColumnName")+" "+
rs.getString("yourThirdColumnName"));
}
Really you should use PreparedStatement. In your case though you are not using any parameterizedQuery but One of the major benefits of using PreparedStatement is better performance. PreparedStatement gets pre compiled.
In database and there access plan is also cached in database, which allows database to execute parametric query written using prepared statement much faster than normal query because it has less work to do. You should always try to use PreparedStatement.
So you can do something like this
String query = "SELECT GamerTag FROM backup"
PreparedStatement st =connect.prepareStatement("query");
ResultSet rs = st.executeQuery();

Create method which returns resultset from sql query

I have a little problem with creating a method which takes String as parameter and return ResultSet after execute the query.Here is an example actually what I'm trying to do :
public ResultSet executeSQLQuery(String query){
ResultSet rs = sqliteDb.rawQuery(query,null);;
return rs;
}
Something like this, but it says that I have to convert rs to cursor type, but I need to return RS. Any ideas how to get the things to work?
possible duplicate
The result set isn't available, at least for now, in sqlite. It all depends on exactly what information you want from the ResultSet or ResultSetMetaData, etc, but there are other means of obtaining almost the same information.
check this link
to get resultset from pre-complie statement in android

Search a ResultSet for a specific value method?

Is there a ResultSet method that I can use that would search through a ResultSet and check whether it has the specific value/element?
Similar to ArrayList.contains() method.
If there isn't, you don't need to type up a search method, I'll make one :)
Thanks in advance.
Don't do the search in Java side. That's unnecessarily slow and memory hogging. You're basically taking over the job the DB is designed for. Just let the DB do the job it is designed for: selecting and returning exactly the data you want with help of the SQL language powers.
Start learning the SQL WHERE clause. For example, to check if an username/password mathes, do:
connection = database.getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM user WHERE username=? AND password=md5(?)");
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
// Match found!
} else {
// No match!
}
Assuming you mean a SQL ResultSet, the answer is no, you have to write one. The JDBC driver usually won't retrieve all the rows at once (what if the query returned 1 million rows). You will have to read the rows and filter them yourself.

SQLException: JZ0S4: Cannot execute an empty (zero-length) query. on a Prepared Statement

Heres a class executing PreparedStatements on a Connection.
public class doSomething {
private PreparedStatement ps;
public setPS (Connection conn) throws SQLException {
String sql = "select * from table where id = ?";
ps = conn.prepareStatement(sql);
}
public void runSomething(String var){
ps.setString(1,var);
ResultSet rs = ps.executeQuery();
...
}
}
I call
doSomethingInstance.setPS(conn);
doSomethingInstance.runSomething(var);
from another class and this throws and exception at the
ResultSet rs = ps.executeQuery();
The exception is SQLException: JZ0S4: Cannot execute an empty (zero-length) query. on a Prepared Statement. I cant understand why. Does anyone see what Iam doing wrong here?
Thanks!
Go back and copy the code straight from your source file, then edit your question. You have a potential ambiguity: Your first fragment calls the prepared statement "preparedStatement", then you change to "prepareStatement" (without the "d"). Having a clean look at your source code will make isolating the problem easier. Do you have two variables or did you mistype your example?
[later...]
Thanks for updating your code. I'm not seeing an obvious problem with it. Have you stepped through it with a debugger (e.g., in Eclipse) to ensure that the two methods are being called as expected?
This issue has been fixed folks. There was a problem with the database permissions. Catching and printing the stacktrace on
ResultSet rs = ps.executeQuery();
indicated that the table being accessed by the query was not found. I still have to figure out why the SQLException: JZ0S4: Cannot execute an empty (zero-length) query is being thrown.
Thanks for your time and consideration.
Rohan
can you print the contents of sql before executing the query? I suspect it's losing it's contents
Is var non null? Is var of the correct type(int instead of String I would think?)

Categories