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

SQL Anywhere 11.0.1 (中文) » SQL Anywhere 服务器 - 编程 » SQL Anywhere 数据访问 API » SQL Anywhere JDBC 驱动程序

 

从 JDBC 客户端应用程序连接

使用 iAnywhere JDBC 驱动程序时,数据库元数据始终可用。

如果希望从使用 jConnect 的 JDBC 应用程序访问数据库系统表(数据库元数据),必须向数据库添加一组 jConnect 系统对象。这些过程会缺省安装到所有数据库。dbinit -i 选项会阻止此安装。

有关向数据库添加 jConnect 系统对象的详细信息,请参见使用 jConnect JDBC 驱动程序

以下完整的 Java 应用程序是一个命令行程序,它连接到正在运行的数据库,在命令行中输出一组信息,然后终止。

对于任何 JDBC 应用程序,要使用数据库数据,第一步都必须建立连接。

此示例中所示的外部连接是常规的客户端/服务器连接。有关如何从运行于数据库服务器内部的 Java 类创建内部连接的信息,请参见从服务器端的 JDBC 类建立连接

连接示例代码

以下是用来建立连接的方法的源代码。源代码可在 samples-dir\SQLAnywhere\JDBC 目录的 JDBCConnect.java 文件中找到。如所显示的那样,该示例使用 JDBC 3.0 版本的 iAnywhere JDBC 驱动程序连接到数据库。要使用 jConnect 6.0.5 驱动程序,请将 ianywhere.ml.jdbcodbc.jdbc3.IDriver 替换为 com.sybase.jdbc3.jdbc.SybDriver。如果要使用 jConnect 6.0.5 驱动程序,还必须更改连接字符串。替换代码以注释的形式包含在源代码中。

import java.io.*;
import java.sql.*;

public class JDBCConnect
{
  public static void main( String args[] )
  {
    try
    {
      // Select the JDBC driver. May throw a SQLException.
      // Choices are jConnect 6.0 driver
      // or iAnywhere JDBC 3.0 driver.
      // Currently, we use the iAnywhere JDBC 3.0 driver.
      DriverManager.registerDriver( (Driver)
        Class.forName(
        // "com.sybase.jdbc3.jdbc.SybDriver").newInstance()
        "ianywhere.ml.jdbcodbc.jdbc3.IDriver").newInstance()
        );

      // Create a connection. Choices are TDS using jConnect,
      // Sun's JDBC-ODBC bridge, or the iAnywhere JDBC driver.
      // Currently, we use the iAnywhere JDBC driver.
      Connection con = DriverManager.getConnection(
        // "jdbc:sybase:Tds:localhost:2638", "DBA", "sql");
        // "jdbc:odbc:driver=SQL Anywhere 11;uid=DBA;pwd=sql" );
        "jdbc:ianywhere:driver=SQL Anywhere 11;uid=DBA;pwd=sql" );

      // Create a statement object, the container for the SQL
      // statement. May throw a SQLException.
      Statement stmt = con.createStatement();

      // Create a result set object by executing the query.
      // May throw a SQLException.
      ResultSet rs = stmt.executeQuery(
        "SELECT ID, GivenName, Surname FROM Customers");

      // Process the result set.
      while (rs.next())
      {
        int value = rs.getInt(1);
        String FirstName = rs.getString(2);
        String LastName = rs.getString(3);
        System.out.println(value+" "+FirstName+" "+LastName);
      }
      rs.close();
      stmt.close();
      con.close();
    }
    catch (SQLException sqe)
    {
      System.out.println("Unexpected exception : " +
                sqe.toString() + ", sqlstate = " +
                sqe.getSQLState());
      System.exit(1);
    }
    catch (Exception e)
    {
      e.printStackTrace();
      System.exit(1);
    }

    System.exit(0);
  }
}

连接示例如何工作
运行连接示例
从服务器端的 JDBC 类建立连接
有关 JDBC 连接的几点说明