Using Java I want to obtain all IDs from my database and select GW_STATUS if it is equal to 0. I used the following SQL statement to achieve this.
PreparedStatement get_id = con.prepareStatement("SELECT ID from SF_MESSAGES where GW_STATUS = 0");
Once the IDs have been obtained, I want to update GW_STATUS to 1 according to their ID as demonstrated in the code below but only one field is being updated when I execute the code.
PreparedStatement update = con.prepareStatement("update SF_MESSAGES set GW_STATUS=? where ID = ?");
update.setInt(1,1);
ResultSet x = get_id.executeQuery();
while(x.next()){
int uber = x.getInt(1);
int array[] = new int[] {uber};
for (int value : array) {
System.out.println("Value = " + value); //Successfully obtains and prints each ID from the databse table
update.setInt(2,value); // Only one ID is updated therefore only field updated
}
}
int result = update.executeUpdate();
System.out.println(result + " Records updated");
I've tried using another update statement within the for loop to update every ID obtained but that doesn't work too. How can I successfully update every field according to their ID?
You can make the whole processing much simple. It turns out that you just want to update SF_MESSAGES which have GW_STATUS equals to 0, so your query can look like the following:
update SF_MESSAGES set GW_STATUS=1 where GW_STATUS=0
Therefore, you do not have to fetch IDs, loop over them so it is more efficient solution.
Related
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 2 ResultSets. 1st ResultSet contains the records from table1 from database1 and 2nd ResultSet contains the records from table2 from database2. I need a list of records from resultset1 which are not present in resultSet2. For this I wrote this logic but it is not working and throwing me the following error.
java.sql.SQLException: Invalid operation for read only resultset: deleteRow
if ( table1ResultSet != null )
{
while ( table1ResultSet.next() )
{
final String table1Record = table1ResultSet.getString( 1 );
if ( table2ResultSet != null )
{
while ( table2ResultSet.next() )
{
final String table2Record = table2ResultSet.getString( 1 );
if ( table1Record.toString().equalsIgnoreCase( table2Record.toString() ) )
{
table1ResultSet.deleteRow();
break;
}
}
}
}
}
return table1ResultSet;
That exception says what the problem is - your result set doesn't support delete. In order to have updateable result set there are some requirements:
When you prepare statement did you make it with ResultSet.CONCUR_UPDATABLE?
A query can select from only a single table without any join operations.
The query must select all non-nullable columns and all columns that do not have a default value. A query cannot use "SELECT * ". Cannot select derived columns or aggregates such as the SUM or MAX of a set of columns.
You might want to move the results sets into Java sets before working doing what you are doing though because using deleteRow will actually delete the row from the database (unless that's the expected result)
There is another problem with your code though. Even if delete works your code will fail on the second iteration of result set 1 because you never reset table2ResultSet and for the second iteration there won't be more results in table2resulset.
But on top of all that. Why would you go through all that hussle and get all that rows that you don't need instead of doing it with one single query like:
select * from table 1 where id not in select id from table 2
or
delete from table 1 where id not in select id from table 2
if that's the goal
Your logic:
Assumes the records come in some order (which may or may not be true, depending on your SQL)
Consumes the entire result set 2 for each row of result set 1, which is unlikely your intent
Deletes things, which is also not what you mentioned in the question
Your question can be implemented easily as such:
Set<String> list1 = new HashSet<>();
while (table1ResultSet.next())
list1.add(table1ResultSet.getString(1).toLowerCase());
while (table2ResultSet.next())
list1.remove(table2ResultSet.getString(1).toLowerCase());
System.out.println(list1);
This will print all the values (without duplicates) that are present in the first result set, but not in the second.
I have an entity named Item in which i have declared a property
#Column(name="ITEM_CODE", unique = true, length=30)
private String itemCode
while inserting a new item in the corresponding table i am trying to generate a unique code by prefixing it PRO- and then concatenating a random number generated by using Random class.
I am also trying to get the last item id inserted in the database and add 1 with the id and then add it to the product code as suffix.
My code to fulfill my purpose is
public String generateItemCode() {
String query = "SELECT max(i.id) FROM ITEM i";
List list = sessionFactory.getCurrentSession().createQuery(query).list();
int nextInsertId = ((Integer) list.get(0)).intValue() + 1;
Random random = new Random();
int number = random.nextInt(9999 - 1 + 1) + 1;
return "" + number+nextInsertId;
}
I have also tried by using this line of code in the method body.
int maxId= (Integer)sessionFactory.getCurrentSession().createQuery("select max(id) from items").uniqueResult();
the above code is not working.
How can i get the last inserted id. Is there any simpler way to do it?
Thanks in advance.
It appears your issue may likely be because of your query syntax mimicing that of native SQL when in reality you aren't asking Hibernate to execute a native query but instead a HQL/JPQL query.
If we assume your entity is named Item with an identifier property named id, you would use:
SELECT max(i.id) FROM Item i
You'll notice I use the property name id and the entity name Item (case is important here).
To put the pieces together, the following should work:
// be sure to check for null lastId in case you have no items.
final String sql = "SELECT max( i.id ) FROM Item i";
Integer lastId = (Integer) session.createQuery( sql ).uniqueResult();
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);
I'm trying to get the new rating from an UPDATE statement in java
int userID = 99;
String sql = "UPDATE table SET rating=rating+1 WHERE user_REF="+userID;
statement.executeUpdate(sql);
I can just do another SELECT statement, but isn't there a better way to retrieve the value or row while updating?
In short, No, there is no way to do this with ANSI standard SQL.
You have three options:
1) Do it in two queries - the update, then the select
2) Create a stored procedure that will execute the update and then return the select
3) Use a DB-specific extension, such as the PostgreSQL RETURNING clause
Note that options 2) and 3) are database-specific.
In MySQL:
$query1 = 'UPDATE `table` SET rating = (#rating:= rating) + 1 WHERE id = 1';
$query2 = 'select #rating';
thanks for the replies everybody, i ended up doing it like this:
int userID = 99;
String sql = "SELECT id, rating FROM table WHERE user_REF="+userID;
ResultSet rs = statement.executeQuery(sql);
rs.first();
float oldRating = rs.getFloat("rating");
float newRating = oldRating +1;
rs.updateFloat("rating", newRating);
rs.updateRow();
return newRating;
that way it (or at least seems so) does only one query to find the correct row, or am i wrong?
In PostgreSQL there is RETURNING clause
See: http://www.postgresql.org/docs/8.3/interactive/sql-update.html
Be cautious that most solutions are database dependent (Whether or not you want database independence in your application ofcourse matters).
Also one other solution you could try is to write a procedure and execute it as follows
my_package.updateAndReturnRating(refId, cursor record).
Of course this may/may not make the solution itself complicated but worth an "evaluation" atleast.