源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

详解Java的JDBC中Statement与PreparedStatement对象

  • 时间:2022-08-29 10:36 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:详解Java的JDBC中Statement与PreparedStatement对象
一旦获得一个连接,我们可以与数据库进行交互。在JDBC Statement, CallableStatement 和 PreparedStatement 接口定义的方法和属性,使可以发送SQL或PL/SQL命令和从数据库接收数据。 它们还定义方法,帮助Java和数据库使用SQL数据类型之间转换数据的差异。 下表提供了每个接口的用途概要,了解决定使用哪个接口 [img]http://img.1sucai.cn/uploads/article/2018010710/20180107100153_0_81264.jpg[/img] [b]Statement 对象: [/b] [b]创建Statement对象 [/b]在可以使用Statement对象执行SQL语句,需要使用Connection对象的createStatement( )方法创建一个,如下面的示例所示:
Statement stmt = null;
try {
  stmt = conn.createStatement( );
  . . .
}
catch (SQLException e) {
  . . .
}
finally {
  . . .
}
一旦创建了一个Statement对象,然后可以用它来与它的三个执行方法之一执行SQL语句。 boolean execute(String SQL) : 如果ResultSet对象可以被检索返回布尔值true,否则返回false。使用这个方法来执行SQL DDL语句,或当需要使用真正的动态SQL。 int executeUpdate(String SQL) : 返回受影响的SQL语句执行的行的数目。使用此方法来执行,而希望得到一些受影响的行的SQL语句 - 例如,INSERT,UPDATE或DELETE语句。 ResultSet executeQuery(String SQL) : 返回ResultSet对象。当希望得到一个结果集使用此方法,就像使用一个SELECT语句。 [b]关闭 Statement 对象: [/b]正如关闭一个Connection对象来保存数据库资源,出于同样的原因,也应该关闭Statement对象。 close()方法简单的调用将完成这项工作。如果关闭了Connection对象首先它会关闭Statement对象也是如此。然而,应该始终明确关闭Statement对象,以确保正确的清除。
Statement stmt = null;
try {
  stmt = conn.createStatement( );
  . . .
}
catch (SQLException e) {
  . . .
}
finally {
  stmt.close();
}

[b]PreparedStatement 对象 [/b]PreparedStatement接口扩展了Statement接口,让过一个通用的Statement对象增加几个高级功能。 statement 提供动态参数的灵活性。 [b]创建PreparedStatement 对象: [/b]
PreparedStatement pstmt = null;
try {
  String SQL = "Update Employees SET age = ? WHERE id = ?";
  pstmt = conn.prepareStatement(SQL);
  . . .
}
catch (SQLException e) {
  . . .
}
finally {
  . . .
}
在JDBC中所有的参数都被代表?符号,这是已知的参数标记。在执行SQL语句之前,必须提供值的每一个参数。 setXXX()方法将值绑定到参数,其中XXX表示希望绑定到输入参数值的Java数据类型。如果忘了提供值,将收到一个SQLException。 每个参数标记是由它的序号位置引用。第一标记表示位置1,下一个位置为2 等等。这种方法不同于Java数组索引,以0开始。 所有的Statement对象的方法来与数据库交互(a) execute(), (b) executeQuery(), 及(c) executeUpdate() 也与PreparedStatement对象的工作。然而,该方法被修改为使用SQL语句,可以利用输入的参数。 [b]关闭PreparedStatement对象: [/b]正如关闭Statement对象,出于同样的原因,也应该关闭的PreparedStatement对象。 close()方法简单的调用将完成这项工作。如果关闭了Connection对象首先它会关闭PreparedStatement对象。然而,应该始终明确关闭PreparedStatement对象,以确保正确的清除。
PreparedStatement pstmt = null;
try {
  String SQL = "Update Employees SET age = ? WHERE id = ?";
  pstmt = conn.prepareStatement(SQL);
  . . .
}
catch (SQLException e) {
  . . .
}
finally {
  pstmt.close();
}

[b]PreparedStatement实例 [/b]以下是这使得使用PreparedStatement以及打开和关闭statments的例子: 复制下面的例子中JDBCExample.java,编译并运行,如下所示:
//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
  // JDBC driver name and database URL
  static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
  static final String DB_URL = "jdbc:mysql://localhost/EMP";

  // Database credentials
  static final String USER = "username";
  static final String PASS = "password";
  
  public static void main(String[] args) {
  Connection conn = null;
  PreparedStatement stmt = null;
  try{
   //STEP 2: Register JDBC driver
   Class.forName("com.mysql.jdbc.Driver");

   //STEP 3: Open a connection
   System.out.println("Connecting to database...");
   conn = DriverManager.getConnection(DB_URL,USER,PASS);

   //STEP 4: Execute a query
   System.out.println("Creating statement...");
   String sql = "UPDATE Employees set age=? WHERE id=?";
   stmt = conn.prepareStatement(sql);
   
   //Bind values into the parameters.
   stmt.setInt(1, 35); // This would set age
   stmt.setInt(2, 102); // This would set ID
   
   // Let us update age of the record with ID = 102;
   int rows = stmt.executeUpdate();
   System.out.println("Rows impacted : " + rows );

   // Let us select all the records and display them.
   sql = "SELECT id, first, last, age FROM Employees";
   ResultSet rs = stmt.executeQuery(sql);

   //STEP 5: Extract data from result set
   while(rs.next()){
     //Retrieve by column name
     int id = rs.getInt("id");
     int age = rs.getInt("age");
     String first = rs.getString("first");
     String last = rs.getString("last");

     //Display values
     System.out.print("ID: " + id);
     System.out.print(", Age: " + age);
     System.out.print(", First: " + first);
     System.out.println(", Last: " + last);
   }
   //STEP 6: Clean-up environment
   rs.close();
   stmt.close();
   conn.close();
  }catch(SQLException se){
   //Handle errors for JDBC
   se.printStackTrace();
  }catch(Exception e){
   //Handle errors for Class.forName
   e.printStackTrace();
  }finally{
   //finally block used to close resources
   try{
     if(stmt!=null)
      stmt.close();
   }catch(SQLException se2){
   }// nothing we can do
   try{
     if(conn!=null)
      conn.close();
   }catch(SQLException se){
     se.printStackTrace();
   }//end finally try
  }//end try
  System.out.println("Goodbye!");
}//end main
}//end JDBCExample

现在来编译上面的例子如下:
C:>javac JDBCExample.java
当运行JDBCExample,它会产生以下结果:
C:>java JDBCExample
Connecting to database...
Creating statement...
Rows impacted : 1
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 35, First: Zaid, Last: Khan
ID: 103, Age: 30, First: Sumit, Last: Mittal
Goodbye!

  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部