样本 Java 应用程序的概述

本主题描述 DB2eAppl.javaDB2eJavaCLP.java 样本应用程序。

样本 1:DB2eAppl.java

DB2eAppl.java 演示如何编写用于 DB2 Everyplace 的 JDBC 程序。

DB2eAppl.java 应用程序的主要步骤包括:

步骤 1:
导入 java.sql 包。

步骤 2:
装入 DB2 Everyplace JDBC 驱动程序 com.ibm.db2e.jdbc.DB2eDriver

步骤 3:
连接至当前目录(DB2eAppl.java 应用程序将在该目录中运行)中的数据库。

步骤 4:
创建“语句”对象。

步骤 5:
设置非常简单的样本数据库,该数据库由包含两个记录的 EMPLOYEE 表组成。这是通过使用 java.sql.Statement 接口的 executeUpdate(String sql) 方法完成的。

步骤 6:
从 EMPLOYEE 表中选择所有记录,然后通过使用 java.sql.ResultSet 接口的 next() 方法来检索这些行。

步骤 7:
从数据库删除 EMPLOYEE 表并释放数据库和 JDBC 资源。

以下 DB2eAppl.java 源代码包含一些注释,这些注释显示正在何处使用以上说明的步骤。

import java.sql.*; //Step 1
 
public class DB2eAppl
{
    public static void main(String[] args) {
 
        String driver ="com.ibm.db2e.jdbc.DB2eDriver";
String url = "jdbc:db2e:mysample"; 
            try {
            Class.forName(driver);//Step 2
            Connection con = DriverManager.getConnection(url);//Step 3
            Statement st = con.createStatement();//Step 4
 
            //Create table: employee  //Step 5
            st.executeUpdate("CREATE TABLE employee (EMPNO CHAR(6), FIRSTNAME VARCHAR(12))");
            System.out.println("*** Created table: employee");
 
			//Add records to employee  
            st.executeUpdate("INSERT INTO employee VALUES ('112233','John')");
            st.executeUpdate("INSERT INTO employee VALUES ('445566','Mary')");
            System.out.println("*** Inserted two records");
 
            //Query and display results //Step 6
            ResultSet rs = st.executeQuery("SELECT * FROM employee");
            System.out.println("*** Query results:");
            while (rs.next()) {
                System.out.print("EMPNO=" + rs.getString(1) + ", ");
                System.out.println("FIRSTNAME=" + rs.getString(2));
            }
 
            //Delete table: employee  //Step 7
            st.executeUpdate("Drop table employee");
            System.out.println("*** Deleted table: employee");
 
			rs.close();
			st.close();
			con.close();
 
        } catch (SQLException sqlEx) {
            while(sqlEx !=null)
            {
                System.out.println("[SQLException] " +
                                   "SQLState: " + sqlEx.getSQLState() + 
                    ",Message:"+sqlEx.getMessage()+
                    ",Vendor:"+sqlEx.getErrorCode());
                sqlEx =sqlEx.getNextException();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

样本 2:DB2eJavaCLP.java

DB2eJavaCLP.java 是用于 DB2 Everyplace 的 Java 命令行处理器。

限制:
在 Palm OS 上,不支持 DB2eJavaCLP.java 样本应用程序。

相关任务

相关概念