Reputation: 790
I have a table named Domain_Test
and column are:-
Here ID
is auto increment
and Domain
contains links and processed
contains 0. Basically i need a query through which I can retrieve the domain
and at the same time need to update processed
column to 1. And I'm using java to do all this.
Upvotes: 1
Views: 1152
Reputation: 2646
Try with this,
public static int retrieveAndUpdate(Connection connection) throws SQLException{
try {
connection.setAutoCommit(false);
String querySelect = "SELECT processed FROM Domain_Test WHERE id=YourId";
String queryUpdate = "UPDATE Domain_Test SET processed=? WHERE id=YourId";
PreparedStatement preparedStatement = connection.prepareStatement(queryUpdate);
ResultSet resultSet = connection.createStatement().executeQuery(querySelect);
if (!resultSet.next()) {
return 0;
} else { // This block is running, if the query is retrieved some data
while (resultSet.next()) {
preparedStatement.setInt(1, 1);
preparedStatement.addBatch();
}
int[] batchUpdate = preparedStatement.executeBatch();
for (int result : batchUpdate) {
if (result == 0) {
connection.rollback();// When update process gets an error, stop the current process.
return 0;
}
}
}
connection.commit(); //If Retrieving and Updating is success, data will be commited to the DB
return 1;
} catch (SQLException ex) {
connection.rollback(); // // When update process gets SQLException, current process will be stopped.
throw ex;
}
}
This will be commit your data to DB, if all the processes are succeed.
Upvotes: 1
Reputation: 35583
you cannot retrieve
and update
in a single statement, there are 2 steps
select domain from thatTable where id = 100 -- retrieve the value in domain
to update:
update thatTable set processed = NOW() where id = 100
Upvotes: 2
Reputation: 1176
As far as I know this is not possible. I am assuming the reason you want to do it in a single statement is to make sure the record is not updated between your two statements.
What you need to do is to use a transaction. Inside the transaction, first do the update, then the select. Then you commit the transaction. The atomicity of the transaction guarantees that the value of the doman you read is the same as when you set the processed flag.
START TRANSACTION;
UPDATE Domain_Test SET processed=1 WHERE id=YourId
SELECT Doman FROM Domain_Test WHERE id=YourId
COMMIT;
For more info about transactions in mysql, see http://dev.mysql.com/doc/refman/5.0/en/commit.html .
Upvotes: 2