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

Exemple de soumission et de rollback JDBC

Voici un exemple, ce qui utilisecommitetrollbackIl est décrit dans le tutoriel sur les transactions JDBC.

Ce code d'exemple est écrit en fonction des paramètres de l'environnement et de la base de données des quelques chapitres précédents.

Copiez et collez l'exemple suivant dans le fichier JDBCExample.java, puis compilez et exécutez comme suit :

//步骤1.导入所需的软件包
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;
   Statement stmt = null;
   try{
      //步骤2:注册JDBC驱动程序
      Class.forName("com.mysql.jdbc.Driver");
      //步骤3:建立连接
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);
      //步骤4:将自动提交设置为false。
      conn.setAutoCommit(false);
      //步骤5:执行查询以创建陈述
      // RS示例的必需参数。
      System.out.println("Creating statement...");
      stmt = conn.createStatement();
                           ResultSet.TYPE_SCROLL_INSENSITIVE,
                           ResultSet.CONCUR_UPDATABLE);
     
      //步骤6:在“员工”表中插入一行
      System.out.println("Inserting one row....");
      String SQL = "INSERT INTO Employees " +
                    "VALUES (106, 20, 'Rita', 'Tez')";
      stmt.executeUpdate(SQL);  
      //步骤7:在“员工”表中再插入一行
      SQL = "INSERT INTO Employees " +
                    "VALUES (107, 22, 'Sita', 'Singh')";
      stmt.executeUpdate(SQL);
      //步骤8:在此处提交数据。
      System.out.println("Commiting data here....");
      conn.commit();
	  
	  //步骤9:现在列出所有可用的记录。
      String sql = "SELECT id, first, last, age FROM Employees";
      ResultSet rs = stmt.executeQuery(sql);
      System.out.println("List result set for reference....");
      printRs(rs);
      //步骤10:清理环境
      rs.close();
      stmt.close();
      conn.close();
   }catch(SQLException se){
      //处理JDBC错误
      se.printStackTrace();
      // 如果有错误,则回滚更改。
      System.out.println("Rolling back data here....");
	  try{
		 if(conn!=null)
            conn.rollback();
      }catch(SQLException se2){
         se2.printStackTrace();
      }//结束尝试
   }catch(Exception e){
      //处理Class.forName的错误
      e.printStackTrace();
   }finally{
      //用于关闭资源
      try{
         if(stmt!=null)
            stmt.close();
      }catch(SQLException se2){
      
      }
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }
   }
   System.out.println("Goodbye!");
}//结束main
   public static void printRs(ResultSet rs) throws SQLException{
      //确保我们从第一行开始
      rs.beforeFirst();
      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(", Premier : ") + first);
         System.out.println(", Dernier : ", + last);
     }
     System.out.println();
   }//Fin de printRs()
}//Fin de JDBCExample

Compilons maintenant l'exemple ci-dessus, comme suit :

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

Au moment de l'exécutionJDBCExampleIl produira les résultats suivants :-

C:\>java JDBCExample
Connexion à la base de données...
Création de l'instruction...
Insertion d'une ligne....
Commit des données ici....
Liste de l'ensemble de résultats pour référence....
ID : 10, Âge : 18, Premier : Zara, Dernier : Ali
ID : 101, Âge : 25, Premier : Mahnaz, Dernier : Fatma
ID : 102, Âge : 3, Premier : Zaid, Dernier : Khan
ID : 103, Âge : 28, Premier : Sumit, Dernier : Mittal
ID : 106, Âge : 2, Premier : Rita, Dernier : Tez
ID : 107, Âge : 22, Premier : Sita, Dernier : Singh
Au revoir !
C:\>