如何使用JDBC API删除Oracle数据库表中的所有记录?


SQL 的 **TRUNCATE** 语句用于删除表中的所有记录。

语法

TRUNCATE TABLE table_name;

要使用 JDBC API 删除表中的所有记录,您需要:

**注册驱动程序:** 使用 **DriverManager** 类的 **registerDriver()** 方法注册驱动程序类。将驱动程序类名作为参数传递给它。

**建立连接:** 使用 **DriverManager** 类的 **getConnection()** 方法连接到数据库。将 URL(字符串)、用户名(字符串)、密码(字符串)作为参数传递给它。

**创建语句:** 使用 **Connection** 接口的 **createStatement()** 方法创建一个 Statement 对象。

**执行查询:** 使用 Statement 接口的 **execute()** 方法执行查询。

下面的 JDBC 程序建立与 Oracle 数据库的连接,并删除名为 dispatches 的表中的所有记录:

示例

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DeletingAllRows_Oracle {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
      //Getting the connection
      String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe";
      Connection con = DriverManager.getConnection(oracleUrl, "system", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();
      //Query to delete all records in a table
      String query = "Truncate table DISPATCHES";
      //Executing the query
      stmt.execute(query);
      System.out.println("Table truncated....");
   }
}

输出

Connection established......
Table truncated....

删除后,如果您使用 select 语句验证 Dispatches 表的内容,您将得到以下输出:

SQL> select * from dispatches;
no rows selected

更新于:2019年7月30日

2K+ 次浏览

启动您的 职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.