ResultSet not positioned properly, perhaps you need to call next [duplicate] - java

This question already has answers here:
PSQLException: ResultSet not positioned properly, perhaps you need to call next
(4 answers)
Closed 3 years ago.
Hi I have problem with this code as it seems to always return the SQL Exception. It was working for a few goes then stopped and came back with exception. so I'm not sure what's wrong.
I have tried to change the vld.close() to different places before so yeah. Thanks
PreparedStatement vld = conn.prepareStatement("SELECT * FROM carsharing.available(?,?,?,?)");
vld.setString(1, carName);
vld.setString(2, memberUser);
vld.setTimestamp(3, new java.sql.Timestamp(startTime.getTime()));
vld.setTimestamp(4, new java.sql.Timestamp(endTime.getTime()));
System.out.println("test1");
ResultSet rset = vld.executeQuery();
System.out.println("test2");
rset.next();
int num = rset.getInt("num");
boolean valid = rset.getBoolean("aval");
vld.close();
System.out.println(num);
System.out.println(valid);

1) Verify SQL
Can you verify first that the SQL is correct? It doesn't look correct to me. What you now try to execute is the following SQL:
SELECT * FROM carsharing.available(?,?,?,?)
If you want to limit the resultset by the given name, user and timestamps SQL should look like:
SELECT * FROM carsharing WHERE carNameField=? AND memberUserField=? AND tsField1=? AND tsField2=?
Where you would replace the Field names with the correct column names for your schema.
2) Resultset navigation
Then when you have your resultset after execution you can use first() to navigate to the first position and it also returns boolean so you can check if there even are results available. If you want more values fetched you'll need a loop.
//...
ResultSet rset = vld.executeQuery();
if( rset.first()){
int num = rset.getInt("num");
boolean valid = rset.getBoolean("aval");
}
//...

U need to iterate the result set. U just can't as
rset.next();
The code is
ResultSet rset = vld.executeQuery();
System.out.println("test2");
while(rset.next()) {
int num = rset.getInt("num");
boolean valid = rset.getBoolean("aval");
System.out.println(num);
System.out.println(valid);
}
vld.close();

Related

Combining SET statements with normal statements

I'm trying to create a tool that runs mySQL queries/ statements on a database.
The problem I'm running into is that these queries/ statements are in a free form text like a text box - I'm also using them with a professional SQL program.
To give an example it would be something like:
#Example of a query statement
#SET fName = "John"
SELECT * FROM Person WHERE Person.firstName = fName
#Example of an execute statement
#SET fName = "John"
DELETE FROM Person WHERE Person.firstName = fName
As you can see the query/ statements may contain comments, SET statements and then either an execute statement or a select query. Also they may not always be properly formatted so there may be empty lines between stuff or tabs or spaces.
I know about the option with PreparedStatements, but while that would work it doesn't really fit the bill of the whole query/ statement being editable as freeform text.
My question is how to execute these statements/ queries through Java? executeBatch would work for the second example, but not the first as it's returning a ResultSet.
Solution comes out to using Statement.execute() rather than one of the more specific functions like .executeUpdate() or .executeQuery() or even .executeBatch()
The function .execute() returns a boolean to say whether there are results returned or if there are more results to get.
public void executeAll(String queryString) throws SQLException {
boolean hasMoreResults = statement.execute(queryString);
int updateCount = statement.getUpdateCount();
while(hasMoreResults || (!hasMoreResults && updateCount != -1)){
//.execute() can be false if a query is not returned as when using a SET/ UPDATE/ DELETE which is why we check if updateCount is -1 meaning there are no more statements returned
if(hasMoreResults){
resultSet = statement.getResultSet();
//Do what you need to do with the ResultSet
} else {
//Else it's a UPDATE/ DELETE count - int
//Do what you need to do with the updateCount
}
hasMoreResults = statement.getMoreResults();
updateCount = statement.getUpdateCount();
//New values for the next cycle
}
//Possibly return stuff?
}

My java program isn't counting database rows correctly

I'm making a program and I have to get the number of rows in a MySQL database. My table has 4 rows but for some reason I'm getting the number 1 everytime I run the program. Here is my code:
public static void showItems() throws Exception {
try{
Connection con = getConnection();
Statement search = con.createStatement();
ResultSet rs = search.executeQuery("SELECT COUNT(id) FROM main;");
int rows = 0;
rs.beforeFirst();
while (rs.next()){
rows++;
}
System.out.println(rows);
Can someone help me? What am I doing wrong here?
I tried many different ways and none returns me the correct value.
Thanks in advance!
Your query returns one row and contains the value 4 (the count of the number of rows in the table).
Run your query directly in a database client and look at what you get.
This bit of code should show you how to get ahold of the "4". Try this loop in place of the one that contains "row++":
while (rs.next()) {
System.out.println(rs.getInt(1));
}

How get the number of rows count by ResultSet in Java [duplicate]

This question already has answers here:
How do I get the row count in JDBC?
(7 answers)
Closed 8 years ago.
I want to get the row count of a ResultSet.
ResultSet rs;
Statement s;
rs=s.executeQuery("SELECT * FROM mytable");
//rs.getRowCount; ???
You can go to the last row of the resultset and get the row number like this:
resultSet.last()
int count = resultSet.getRow()
But this is inefficient because it has to read all the table data. Better to execute the query:
SELECT COUNT(*) FROM mytable
I think we can get count as given below:
int size = 0;
try {
while(rs.next()){
size++;
}
}
catch(Exception ex) { }
or we can use
ResultSet.getRow()

Trying to pass a Java variable into a sql string

I've had a look around on the web but can't seem to find a definite answer to my question.
Basically, I have a database and table that are successfully working. Now I want to read each line from my table one by one and store the result into a array and I am trying to use a for loop to be more professional rather then using repetition.
I have this code
for (int i=1; i<=8; i++)
{
String query = "Select * FROM Table1 WHERE ID = i";
Rs = St.executeQuery(query);
COL1Title[i] = Rs.getString("CO1Name");
COL2Age[i] = Rs.getString("CO2Rating");
}
The for loop is in a try catch statement and it's complaining with the error "Unknown column 'i' in 'where clause'"
Im guessing there's a certain way for how variable i is to be inserted in the the query.
I should point out ID is a column that has the auto increment feature added on and is primary key if that helps
Could anyone help me out here?
First, we can simplify the task be executing a single query. Note the addition of the range limit and the ORDER BY - without an ORDER BY the results have an unspecified order!
PreparedStatement stmt = "Select ID, CO1Name, CO2Rating"
+ " FROM Table1"
+ " WHERE ID >= ? AND ID <= ?"
+ " ORDER BY ID";
And bind in placeholders (unless there is good reason otherwise, always use placeholders when injecting data into a query). The values could have been hard-coded above in this case, just as they are hard-coded in the for-loop, but the binding is shown here for future reference:
stmt.setInt(1, 1);
stmt.setInt(2, 8);
Then execute the query:
ResultSet rs = stmt.executeQuery();
And iterate the results. Note that rs.next() must be invoke once before any column is read (the cursor starts before any records) and, in this case, it makes it easy to handle a bunch of results.
while (rs.next()) {
int id = rs.getInt("ID");
String title = rs.getString("CO1Name");
String name = rs.getString("CO2Rating");
// do stuff with this record
}
Note that even though the ORDER BY guarantees that the results are iterated in order of ID, assuming a database cardinality rule ensures each result has a unique ID, there may be 0 to 8 records returned - that is, non-existent records may need to be detected/handled separately.
Also (but not shown), make sure to cleanup (close) the ResultSet when done: use a try/finally or try-with-resources construct.
You need to pass i in string as integer, Replace line by:
String query = String.format("Select * FROM Table1 WHERE ID = %d",i);

Handling Boolean resultset in java

I have one query that returns string value, my query is
select case when (select count (distinct style_packing_spec_id) from packing_spec_uses_pack p,style_pack sp where sp.style_pack_id=p.style_pack_id and sp.style_id=1701) != (select count (distinct style_packing_spec_id) from style_packing_spec where style_id=1701) then 'DonotProceed' else 'Proceed' end ";
It gives result as below
?case?
----------
DonotProceed
how to execute this is in java, how to handle this result set,I tried like this
String sql="query";
ResultSet rs=stmt.executeQuery(sql);
It returns nullpointerexception
String str=rs.getString(1);
I've never had boolean returned from a query (Oracle doesn't do that...), but I assume that it works. You just need to go to the first row of the result set, and the column index starts with 1 (not 0).
ResultSet rs=stmt.executeQuery(sql);
try{
rs.next(); // move to the first row
return rs.getBoolean(1); // first column is 1
}
finally{
rs.close();
}
Update:
It shows type mismatch error cannot convert from boolean to Boolean
Are you using Java 1.4 ? For Java5 and above, this should be taken care of by auto-boxing. But you can also fix it by using a primitive boolean variable to match what JDBC returns:
boolean str = rs.getBoolean(1); // I question the variable name, though

Categories

Resources