简体   繁体   中英

How to insert and retrieve at the same time in MySQL

I have a table named Domain_Test and column are:-

  1. ID
  2. Domain
  3. Processed

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.

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 .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM