Click here to view and discuss this page in DocCommentXchange. In the future, you will be sent there automatically.

SQL Anywhere 12.0.0 (中文) » SQL Anywhere 服务器 - 编程 » JDBC 支持 » 使用 JDBC 访问数据

 

使用 JDBC 执行插入、更新和删除

静态 SQL 语句 INSERT、UPDATE 和 DELETE 等不返回结果集,使用 Statement 类的 executeUpdate 方法执行。诸如 CREATE TABLE 的语句及其它数据定义语句也可通过使用 executeUpdate 来执行。

也可以使用 Statement 类的 addBatch、clearBatch 和 executeBatch 方法。由于 JDBC 规范对于 Statement 类的 executeBatch 方法的行为没有明确规定,因此在使用 SQL Anywhere JDBC 驱动程序的情况下使用这种方法时应当考虑如下几点:

  • 如果遇到 SQL 异常或结果集,批处理将立即终止。如果批处理停止,executeBatch 方法就会抛出 BatchUpdateException。在 BatchUpdateException 上调用 getUpdateCounts 方法会返回一个行计数整数数组。批处理失败之前的计数集会包含一个有效的非负更新计数;而在批处理失败点及其之后,计数集会包含一个 -1 值。将 BatchUpdateException 转换到 SQLException 时会提供有关批处理停止原因的更多详情。

  • 只有在显式调用 clearBatch 方法时批处理才会被清除。因此,重复调用 executeBatch 方法将会导致再三地重复执行批处理。此外,调用 calling execute(sql_query) 或 executeQuery(sql_query) 能够正确地执行指定的 SQL 查询,但不能清除基础批处理。因此,调用 executeBatch 方法,接着调用 execute(sql_query),然后再次调用 executeBatch 方法,将导致执行成批语句集,再执行指定的 SQL 查询,接下来再次执行成批语句集。

以下代码段说明如何执行 INSERT 语句。它将已传递到 InsertStatic 方法的 Statement 对象用作一个参数。



public static void InsertStatic( Statement stmt )
{
  try
  {
    int iRows = stmt.executeUpdate(
      "INSERT INTO Departments (DepartmentID, DepartmentName)"
      + " VALUES (201, 'Eastern Sales')" );
    // Print the number of rows inserted
    System.out.println(iRows + " rows inserted");
  }
  catch (SQLException sqe)
  {
    System.out.println("Unexpected exception : " +
              sqe.toString() + ", sqlstate = " +
              sqe.getSQLState());
  }
  catch (Exception e)
  {
    e.printStackTrace();
  }
}
可用源代码

此代码段是位于 samples-dir\SQLAnywhere\JDBC 目录中的 JDBCExample Java 文件的一部分。

 注意
 运行 JDBC 的 Insert 示例: