是否可以进行批量更新但是有不同的声明?我找到的每个教程和在线资源都使用相同的语句。这就是我所拥有的,但它不起作用。
public static void resetNotifications(User user)
{
DataSource dataSource = null;
Context initialContext = null;
Context environmentContext = null;
Connection connection = null;
PreparedStatement preparedStatement = null;
String stride = "UPDATE stride SET recipientView = 1 WHERE recipientId = ?";
String strideLike = "UPDATE strideLike SET recipientView = 1 WHERE recipientId = ? ";
String strideCommentMe = "UPDATE strideComment SET recipientView = 1 WHERE recipientId = ? ";
String strideCommentLike = "UPDATE strideCommentLike SET recipientView = 1 WHERE recipientId = ? ";
String strideCommentFollow = "UPDATE strideCommentNotification SET recipientView = 1 WHERE userId = ? ";
try
{
initialContext = new InitialContext();
environmentContext = (Context) initialContext.lookup("java:/comp/env");
dataSource = (DataSource) environmentContext.lookup("jdbc/instride");
connection = dataSource.getConnection();
connection.setAutoCommit(false);
preparedStatement = connection.prepareStatement(stride);
preparedStatement.setLong(1, user.getId());
preparedStatement.addBatch();
preparedStatement = connection.prepareStatement(strideLike);
preparedStatement.setLong(1, user.getId());
preparedStatement.addBatch();
preparedStatement = connection.prepareStatement(strideCommentMe);
preparedStatement.setLong(1, user.getId());
preparedStatement.addBatch();
preparedStatement = connection.prepareStatement(strideCommentLike);
preparedStatement.setLong(1, user.getId());
preparedStatement.addBatch();
preparedStatement = connection.prepareStatement(strideCommentFollow);
preparedStatement.setLong(1, user.getId());
preparedStatement.addBatch();
preparedStatement.executeBatch();
connection.commit();
}
catch(NamingException error)
{
System.out.println("NotificationsDAO - resetNotifications() - Error With JNDI Lookup - " + error.getMessage());
error.printStackTrace();
}
catch(SQLException error)
{
System.out.println("NotificationsDAO - resetNotifications() - Error With SQL - " + error.getMessage());
error.printStackTrace();
}
finally
{
if (initialContext != null) try{initialContext.close();} catch(NamingException ignore) {}
if (environmentContext != null) try{environmentContext.close();} catch(NamingException ignore) {}
if (connection != null) try{connection.close();} catch(SQLException ignore) {}
if (preparedStatement != null) try{preparedStatement.close();} catch(SQLException ignore) {}
}
}
答案 0 :(得分:1)
您不能在一个批处理中执行多个不同的语句,但是,您可以使用一个存储过程,可以在单个往返服务器中完成所有操作,同时保持单个事务的好处
答案 1 :(得分:0)
如果您使用简单的Statement
而不是PrepareStatement
,则可以在一个批处理中执行多个不同的语句。请参阅文档和示例here。