English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JDBC utilise les traitements par lots de l'objet PreparedStatement

C'est une séquence typique d'étapes pour utiliser les traitements par lots avec l'objet PreparedStatement-

  • Créer des instructions SQL en utilisant des placeholders.

  • Utiliser ces deuxprepareStatement()  La méthode crée un objet PreparedStatement.

  • Utiliser pour définir le commit automatique sur false setAutoCommit().

  • utiliseraddBatch()Les méthodes sur l'objet Statement créées par l'opération de création ajoutent un nombre quelconque d'instructions SQL au traitement par lots.

  • utiliserexecuteBatch()创建的语句对象上的方法执行所有SQL语句。

  • 最后,使用commit()方法提交所有更改。

该示例代码是根据前几章中的环境和数据库设置编写的。

复制并粘贴以下示例到JDBCExample.java中,如下编译并运行:

// 导入所需的软件包
import java.sql.*;
public class JDBCExample {
   // JDBC驱动程序名称和数据库URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/EMP";
   //  数据库凭证
   static final String USER = "username";
   static final String PASS = "password";
   
   public static void main(String[] args) {
   Connection conn = null;
   PreparedStatement stmt = null;
   try{
      // 注册JDBC驱动程序
      Class.forName("com.mysql.jdbc.Driver");
      // 打开连接
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);
      // 创建SQL语句
      String SQL = "INSERT INTO Employees(id,first,last,age) "; +
                   "VALUES(?, ?, ?, ?)";
      // 创建preparedStatement
      System.out.println("Creating statement...");
      stmt = conn.prepareStatement(SQL);
      // 将自动提交设置为false
      conn.setAutoCommit(false);
      // 首先,让我们选择所有记录并显示它们。
      printRows( stmt );
  
      // 设置变量
      stmt.setInt( 1, 400 );
      stmt.setString( 2, "Pappu" );
      stmt.setString( 3, "Singh" );
      stmt.setInt( 4, 33 );
      // 将其添加到批
      stmt.addBatch();
      // 设置变量
      stmt.setInt( 1, 401 );
      stmt.setString( 2, "Pawan" );
      stmt.setString( 3, "Singh" );
      stmt.setInt( 4, 31 );
      // 将其添加到批
      stmt.addBatch();
      // 创建一个int []来保存返回的值
      int[] count = stmt.executeBatch();
      //明确提交语句以应用更改
      conn.commit();
      // 同样,让我们选择所有记录并显示它们。
      printRows( stmt );
      // 清理环境
      }catch(SQLException se
      conn.close();
   }catch(SQLException se){
      //处理JDBC错误
      se.printStackTrace();
   }catch(Exception e){
      //处理Class.forName的错误
      e.printStackTrace();
   }finally{
      //用于关闭资源
      try{
         stmt.close();
            }catch(SQLException se
      }2){
      
      }
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }
   }
   System.out.println("Goodbye!");
}//结束main
public static void printRows(Statement stmt) throws SQLException{
   System.out.println("Displaying available rows...");
   // 让我们选择所有记录并显示它们。
   String sql = "SELECT id, first, last, age FROM Employees";
   ResultSet rs = stmt.executeQuery(sql);
   while(rs.next()){
      //按列名检索
      int id  = rs.getInt("id");
      int age = rs.getInt("age");
      String first = rs.getString("first");
      String last = rs.getString("last");
      //显示值
      System.out.print("ID: ",) + id);
      System.out.print(", Age: ",) + age);
      System.out.print(", First: ",) + first);
      System.out.println(", Last: ",) + last);
   }
   System.out.println();
   rs.close();
}//Fin de printRows()
}//Fin de JDBCExample

Maintenant, compilons l'exemple ci-dessus, comme suit :

C:\>javac JDBCExample.java
C:\>

En mode exécutionJDBCExampleIl produira les résultats suivants :-

C:\>java JDBCExample
Connexion à la base de données...
Création de l'instruction...
Affichage des lignes disponibles...
ID : 95, Âge : 20, Premier : Sima, Dernier : Chug
ID : 100, Âge : 35, Premier : Zara, Dernier : Ali
ID : 101, Âge : 25, Premier : Mahnaz, Dernier : Fatma
ID : 102, Âge : 30, Premier : Zaid, Dernier : Khan
ID : 103, Âge : 30, Premier : Sumit, Dernier : Mittal
ID : 110, Âge : 20, Premier : Sima, Dernier : Chug
ID : 200, Âge : 30, Premier : Zia, Dernier : Ali
ID : 201, Âge : 35, Premier : Raj, Dernier : Kumar
Affichage des lignes disponibles...
ID : 95, Âge : 20, Premier : Sima, Dernier : Chug
ID : 100, Âge : 35, Premier : Zara, Dernier : Ali
ID : 101, Âge : 25, Premier : Mahnaz, Dernier : Fatma
ID : 102, Âge : 30, Premier : Zaid, Dernier : Khan
ID : 103, Âge : 30, Premier : Sumit, Dernier : Mittal
ID : 110, Âge : 20, Premier : Sima, Dernier : Chug
ID : 200, Âge : 30, Premier : Zia, Dernier : Ali
ID : 201, Âge : 35, Premier : Raj, Dernier : Kumar
ID : 400, Âge : 33, Premier : Pappu, Dernier : Singh
ID : 401, Âge : 31, Premier : Pawan, Dernier : Singh
Au revoir!
C:\>