我有一个名为Domain_Test
的表,列是: -
此处ID
为auto increment
,Domain
包含链接且processed
包含0.基本上我需要一个查询,通过该查询我可以检索domain
并且同时需要将processed
列更新为1.我使用java来完成所有这些操作。
答案 0 :(得分:2)
据我所知,这是不可能的。我假设您想在单个语句中执行此操作的原因是确保在两个语句之间不更新记录。
您需要做的是使用交易。在事务内部,首先进行更新,然后进行选择。然后你提交交易。事务的原子性保证您读取的doman的值与设置处理标志时的值相同。
START TRANSACTION;
UPDATE Domain_Test SET processed=1 WHERE id=YourId
SELECT Doman FROM Domain_Test WHERE id=YourId
COMMIT;
有关mysql中事务的更多信息,请参阅http://dev.mysql.com/doc/refman/5.0/en/commit.html。
答案 1 :(得分:2)
您在单个声明中无法retrieve
和update
,有两个步骤
select domain from thatTable where id = 100 -- retrieve the value in domain
更新:
update thatTable set processed = NOW() where id = 100
答案 2 :(得分:1)
试试这个,
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;
}
}
如果所有进程都成功,这将把数据提交给DB。