繁体   English   中英

Java PreparedStatement for SQL

[英]Java PreparedStatement for SQL

编写适当的Java语句,使它们成为PreparedStatement ,将讲师ID设置为10101 ,然后找到讲师使用PreparedStatement讲授的课程的标题并执行查询。 您可以假定已经创建了Connection对象conn。

我了解如何编写准备好的语句并执行查询。 我只是不确定如何在一个查询中执行两个查询

PreparedStatement pStmt = conn.prepareStatement(“update instructor set ID = 10101”); 
pStmt.setString(1,11111);
pStmt.executeUpdate();

您可以使用批处理更新。 请在http://tutorials.jenkov.com/jdbc/batchupdate.html中进行检查。

要不然:

如果要在一个调用中向DBMS发送多个命令,则需要使用BEGIN ... END块对它们进行四舍五入。 请检查以下示例:

BEGIN
  UPDATE .... ;
  INSERT .... ;
  (...)
END;

请注意,这是伪代码。

如果使用块BEGIN ... END,则可以发送多个更新,插入,删除等信息; 一些数据库(例如Oracle)接受它。

// the '?' is a placeholder for values
final String sql = "UPDATE instructor SET ID = ?"; // you're probably missing a WHERE clause here, otherwise it will update every instructor to have the same ID
// send the query to the db server for it to prepare
final PreparedStatement updateInstructorIdPstmt = conn.prepareStatement(sql);
// ... 

public void updateInstructorID(final int newId) throws SQLException {
    // set the newId as the parameter for this query execution
    updateInstructorIdPstmt.setInt(1, newId); // '1' means it's the first paramenter.
                                              // it could be 2 or 3 or whatever depending on which '?' it is in your statement
    // execute this update query
    updateInstructorIdPstmt.execute(); // executeUpdate() will return how many rows were updated, if you need to know that info
}

还有其他方法可以对此进行优化,但是它应该使您走上正确的道路。 以这种方式进行操作将使您可以继续为给定的preparestatement执行查询。 您可以有多个preparestatement,每个都有自己的查询来支持。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM