可以说,一个库最重要的部分是它的应用程序编程接口(API)文档。这种文档很多人都熟悉,通常是由 Javadoc生成的。Javadoc 读取代码中的结构化注释并以 HTML 格式输出文档,通常 API 的 包package 在页面左上角的面板中显示,类class 在左下角显示,同时右侧会有库、包或类级别的详细文档(具体取决于在主面板中选择的内容)。例如,Apache Commons Math 的顶级 API 文档如下所示:
以下代码使用 Java 类加载器(Class.forName()调用)将 PostgreSQL 驱动程序代码加载到正在执行的虚拟机中:
import java.sql.*;public class Test1 { public static void main(String args[]) { // Load the driver (jar file must be on class path) [1] try { Class.forName("org.postgresql.Driver"); System.out.println("driver loaded"); } catch (Exception e1) { System.err.println("couldn't find driver"); System.err.println(e1); System.exit(1); } // If we get here all is OK System.out.println("done."); }}
因为类加载器可能失败,失败时会抛出异常,所以将对 Class.forName的调用放在try-catch代码块中。
日常工作中,我经常需要知道为给定的数据库服务器实例定义了哪些用户,这里我使用这个 简便的 SQL来获取所有用户的列表:
import java.sql.*;public class Test3 { public static void main(String args[]) { // Load the driver (jar file must be on class path) [1] try { Class.forName("org.postgresql.Driver"); System.out.println("driver loaded"); } catch (Exception e1) { System.err.println("couldn't find driver"); System.err.println(e1); System.exit(1); } // Set up connection properties [2] java.util.Properties props = new java.util.Properties; props.setProperty("user","me"); props.setProperty("password","mypassword"); String database = "jdbc:postgresql://myhost.org:5432/test"; // Open the connection to the database [3] try (Connection conn = DriverManager.getConnection(database, props)) { System.out.println("connection created"); // Create the SQL command string [4] String qs = "SELECT " + " u.usename AS \"User name\", " + " u.usesysid AS \"User ID\", " + " CASE " + " WHEN u.usesuper AND u.usecreatedb THEN " + " CAST('superuser, create database' AS pg_catalog.text) " + " WHEN u.usesuper THEN " + " CAST('superuser' AS pg_catalog.text) " + " WHEN u.usecreatedb THEN " + " CAST('create database' AS pg_catalog.text) " + " ELSE " + " CAST('' AS pg_catalog.text) " + " END AS \"Attributes\" " + "FROM pg_catalog.pg_user u " + "ORDER BY 1"; // Use the connection to create a statement, execute it, // analyze the results and close the result set [5] Statement stat = conn.createStatement; ResultSet rs = stat.executeQuery(qs); System.out.println("User name;User ID;Attributes"); while (rs.next) { System.out.println(rs.getString("User name") + ";" + rs.getLong("User ID") + ";" + rs.getString("Attributes")); } rs.close; stat.close; } catch (Exception e2) { System.err.println("connecting failed"); System.err.println(e2); System.exit(1); } System.out.println("connection closed"); // If we get here all is OK System.out.println("done."); }}
在上述代码中,一旦有了 Connection实例,它就会定义一个查询字符串(上面的注释[4]),创建一个Statement实例并用其来执行查询字符串,然后将其结果放入一个ResultSet实例。程序可以遍历该ResultSet实例来分析返回的结果,并以关闭ResultSet和Statement实例结束(上面的注释[5])。