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
Related
I have a list of query parameter in my url that I want to use them in my java web service to run a query on a table
public Set<Result> getResult(String query, List<String> sortedQueryParamsValue) {
Connection connection = getConnection();//jdbc connection
//query is some thing like: select * from table A where status = ? and Id = ?
try (PreparedStatement getStatement = connection.prepareStatement(query)) {
for (int i = 0; i <sortedQueryParamKeys.size(); i++) {// sortedQueryParamsValue length is matching the number of values I need for the query and the order matches the order I am expecting
String value = sortedQueryParamsValue.get(i);
getStatement.setString(1, value);
}
try (ResultSet rs = getStatement.executeQuery()) {
while (rs.next()) {
//add to the list of results
}
}
//return the resultset
}
The reason that I used 1 always in getStatement.setString(1, value); is that I thought in each iteration one ? is replaced with the value, but at the end I get some exception back saying java.sql.SQLException: IN or OUT param missing at position 2.
Does anyone knows what I am doing wrong in here?
You can't use 1 every time in getStatement.setString(). You have to increment that number too in order to replace second ? with an actual value.
Since you are only passing 1 all the time and then trying to execute the query, Java is saying that there is no value provided for the second ? when you get java.sql.SQLException: IN or OUT param missing at position 2.
Replacing getStatement.setString(1, value) with getStatement.setString(i+1, value) should do the trick. But you'll have to ensure that the number of elements in sortedQueryParamsValue is equal to the number of ? in your getStatement query.
EDIT: Corrected setString(i,value) to setString(i+1,value) after #Eritrean's comment.
The problem was that passing query parameter through URL to the rest API can have some white spaces and those white spaces causes the query to return empty,
I am going to change 1 to i+1 just to not causing misleading readers
My sql query consists of 5 part which are highly connected to each other. First part creates a temporary table, second part uses that temporary table and creates another temporary table, third part uses the temporary table that created in second part and again creates another temporary table. And the 4th part select some data from 3rd temporary table and 5th part selects the count of 3th temporary table.
Since temporary tables are only usable within a preparedStatement (what I mean is that a temporary table which created by a preparedStatement are not usable from another preparedStatement, I tried that before it is okey) I need to do that within a prepare statement.
So the first 3 part creates temporary tables because of that after setting the parameters to preparedStatement I run preparedStatement.execute() 3 times(I also tried 1....x times) and then I run the preparedStatement.execute() but it returns false which means that there is no resultset. Why is that?
PreparedStatement preparedStatement = conn.prepareStatement("select * into #tmp from tablex where ...\n" +
" select * into #tmp2 from #tmp where ...\n" +
" select * into #tmp3 from #tmp2 where ...\n" +
" select * from #tmp3\n" +
" select count(*) from #tmp3");
Above, I added a simple illustration. Here I need to get the result of 4th and 5th query with prepared statement. How can I do that?
The statements you're executing produce the following results:
An update count
An update count
An update count
A result set
A result set
The meaning of the boolean false returned by execute(String) is:
true if the first result is a ResultSet object; false if it is
an update count or there are no results
This means that you need to use getUpdateCount() to obtain the (first) update count, and getMoreResults() to get the next result (again, this returns a boolean with the same meaning). Only if execute() or getMoreResults() returns false and getUpdateCount() returns -1 are there no more results.
You need to do something like:
boolean nextResultSet = statement.execute(...);
int resultSetCount = 0;
while (true) {
if (nextResultSet) {
resultSetCount++;
try (ResultSet rs = statement.getResultSet()) {
// Do something with result set
}
} else {
int updateCount = statement.getUpdateCount();
if (updateCount == -1) {
// no more results
break;
}
// do something with update count
}
nextResultSet = statement.getMoreResults();
}
You can probably skip part of this complexity by adding SET NOCOUNT ON as the first statement you execute; then you'll not get the update counts and only need to handle the two result sets.
I have the following problem:
I need to set a boolean true is an entry in a database exists.
ResultSet rc1 = null;
int Counterval;
String url = "jdbc:db2://localhost:50000/dbname";
Connection conn = DriverManager.getConnection(url,"","");
Statement st = conn.createStatement();
String sqlmd="select count(*) as Counter from tablename where mdsum = '"+mdSum+"' and filename = '"+Filename+"'";
rc1=st.executeQuery(sqlmd);
Counterval=rc1.getInt("Counter");
System.out.println("VAL: "+Counterval);
conn.close();
I get the following error message:
[jcc][t4][1090][10899][4.19.26] Illigal operation to read at the current cursor position. ERRORCODE=-4476, SQLSTATE=02501
How can I do this?
I use DB2 if that is of importance
Thanks for your help in advance.
TheVagabond
I don't know if you've tried the code, but if you did, what kind of exception are you getting?
You should try st.executeQuery instead of st.executeUpdate and then just compare if the returning number of count() function is bigger than 0
EDIT:
Seeing now your exception in your edited question:
A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
if (rc1.next()){
booleanVariable = true;
}
This will set the boolean variable in true if the variable resultSet (rc1) is returning something, it means that in the database there is data according to the query you made. If it returns false then it is empty.
I hope it can help you. Greets.
You should callResultSet.next() method first to move the cursor to the first row.
boolean check;
String sqlmd="select count(*) as Counter from tablename where mdsum = '"+mdSum+"' and filename = '"+Filename+"'";
rc1=st.executeQuery(sqlmd);
rc1.next();
Counterval=rc1.getInt("Counter");
if(Counterval > 0){
// do something
}else{
// do something
}
System.out.println("VAL: "+Counterval);
According to docs of next method -
Moves the cursor forward one row from its current position. A
ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row; the
second call makes the second row the current row, and so on.
For better understanding read this answer.
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?
}
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);