【发布时间】:2018-04-17 00:36:58
【问题描述】:
我有一个 AWS Lambda 函数,它接受一组参数,我使用 JDBC 批处理将它们全部添加。该进程在 SQL Server DB 中执行存储过程。
这是 Lambda 函数的代码。
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(url, username, password);
connection.setAutoCommit(false);
statement = connection.createStatement();
for (int i = 0; i < notes.getNotes().size(); i++) {
System.out.println("spInsertNewORUpdateNote '" + notes.getNotes().get(i).getNote_id() + "', '" + notes.getNotes().get(i).getUser_id() + "', '" + notes.getNotes().get(i).getNote_text() + "', '" + notes.getNotes().get(i).getNote_timestamp() + "'");
statement.addBatch("spInsertNewORUpdateNote '" + notes.getNotes().get(i).getNote_id() + "', '" + notes.getNotes().get(i).getUser_id() + "', '" + notes.getNotes().get(i).getNote_text() + "', '" + notes.getNotes().get(i).getNote_timestamp() + "'");
}
statement.executeBatch();
connection.commit();
} catch (SQLException e) {
try {
if (connection != null)
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
throw new RuntimeException("400 SQL Error Rolling back");
}
e.printStackTrace();
throw new RuntimeException("400 SQL Error");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("400 Exception");
}finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) { /* ignored */}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) { /* ignored */}
}
}
这是这段代码执行的存储过程。
@note_id varchar(50),
@user_id varchar(50),
@note_text nvarchar(max),
@timestamp date
as
if exists (select * from Notes where note_id = @note_id and Users_user_id =
@user_id)
begin
update Notes set note_text = @note_text where note_id = @note_id and
Users_user_id = @user_id
end
else
begin
insert into Notes values (@note_id,@user_id,@note_text,@timestamp)
end
上述代码仅在批处理只有一条语句时有效。当我包含多个语句时,它会返回以下异常。
前几行只是我在包含在批处理之前打印每个语句。
我已经为此挠头了一段时间,但到目前为止还没有运气。我们将不胜感激。
【问题讨论】:
-
我发现这里可能需要使用CallableStatement Object。所以让我试试吧。
标签: sql-server amazon-web-services stored-procedures jdbc aws-lambda