我有一个带有一些存储过程的Firebird数据库,我正在开发Java Web/Database应用程序。我想知道是否可能以及如何从Java类或servlet调用这些存储过程。
示例:
- 存储过程
deletep
,用于从数据库中删除一行 - 我的WebApp JSP/Servlets
- 我想创建一个执行删除存储过程的链接
要在Java中执行Firebird存储过程,有几种方法。JDBC默认方法将是:
try (CallableStatement cstmt = connection.prepareStatement(
"{call yourProcedure(?, ?, ?)}")) {
cstmt.setString(1, "value1");
cstmt.setString(2, "value2");
cstmt.setString(3, "value3");
cstmt.execute();
}
如果可以选择Firebird存储的过程(即:包含SUSPEND
并可以返回多行(,则需要执行以下操作:
try (CallableStatement cstmt = connection.prepareStatement(
"{call yourProcedure(?, ?, ?)}")) {
cstmt.setString(1, "value1");
cstmt.setString(2, "value2");
cstmt.setString(3, "value3");
try (ResultSet rs = cstmt.executeQuery()) {
while(rs.next()) {
// do something with result set rows ...
}
}
}
如果存储过程可执行并且不返回任何值,这就足够了。如果存储过程可执行(多个(返回列,则需要以下内容:
try (CallableStatement cstmt = connection.prepareStatement(
"{call yourProcedure(?, ?, ?, ?, ?)}")) {
cstmt.setString(1, "value1");
cstmt.setString(2, "value2");
cstmt.setString(3, "value3");
cstmt.registerOutParameter(4, Types.VARCHAR);
cstmt.registerOutParameter(5, Types.VARCHAR)
cstmt.execute();
String out1 = cstmt.getString(4);
String out2 = cstmt.getString(5);
// do something with result
}
另外,您可以使用Firebird特定语法EXECUTE PROCEDURE yourProcedure(?, ?, ?)
进行可执行的存储过程和SELECT * FROM yourProcedure(?, ?, ?)
。
使用jaybird,firebird jdbc驱动程序。
三个步骤:
-
创建一个dbutil java类来存储查询:
public static void deletePlan(Connection conn, CallableStatement statement, String code, String rev, String mention) throws SQLException { statement.setString(1, code); statement.setString(2, rev); statement.setString(3, mention); statement.execute(); }
-
创建Delete Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Connection conn = MyUtils.getStoredConnection(request); String code = request.getParameter("code"); String rev = request.getParameter("revision"); String mention = request.getParameter("mention"); CallableStatement statement = null; try { statement = conn.prepareCall("execute procedure DELETEP(?,?,?)"); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String errorString = null; try { DBUtils.deletePlan(conn, statement, code, rev, mention); } catch (SQLException e) { e.printStackTrace(); errorString = e.getMessage(); } .........
-
在JSP文件中创建删除链接
<a href="${pageContext.request.contextPath}/deletePlan code=${plan.code}&revision=${plan.revision}&mention=${plan.mention}">Delete</a>