是否可以使用 CallableStatement 代替 PreparedStatement?

Can CallableStatement be used in place of PreparedStatement?

需要有关 JDBC 查询的帮助。 我会自己尝试一下,但现在我无法访问数据库。

我的问题是: 由于 CallableStatement 扩展了 PreparedStatement,这是否意味着我们可以使用 CallableStatement 来执行为准备语句准备的任何查询?

更具体地说,像这样使用 Callable 的任何缺点:

CallableStatement stmt = null;
String sql = "UPDATE Employees set age=30 WHERE id=";
      stmt = conn.prepareCall(sql);
      int empID = 102;
      stmt.setInt(1, empID); );
      stmt.execute();
stmt.close();
conn.close();

我们使用 CallableStatement 从数据库调用预定义过程,而不是执行准备好的语句。

准备好的语句:

PreparedStatement pstmt = null;
try {
   String SQL = "Update Employees SET age = ? WHERE id = ?";
   pstmt = conn.prepareStatement(SQL);
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
    pstmt.close();
}

可调用语句:

CallableStatement cstmt = null;
try {
   String SQL = "{call getEmpName (?, ?)}";
   cstmt = conn.prepareCall (SQL);
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   . . .
}

我建议你阅读这篇文章:

http://www.tutorialspoint.com/jdbc/jdbc-statements.htm

是的,你可以。文档中描述的 prepareCall and prepareStatement 方法的差异。如您所见,它们只是针对不同的任务进行了优化。

package com.company;

import java.sql.*;

public class Main {

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");

        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/mysql", "user", "password");

        CallableStatement callableStatement = connection.prepareCall("SELECT * FROM db WHERE user = ?");
        callableStatement.setString(1, "deployer");
        ResultSet resultSet = callableStatement.executeQuery();

        while(resultSet.next()) {
            System.out.println(resultSet.getString("Db"));
        }

        connection.close();
    }
}