随笔-112  评论-73  文章-0  trackbacks-0

Derby现在是apache的一个项目(http://db.apache.org/derby/index.html)。

写了一段简单的代码。以后在项目用到Derby的时候可以查一下。

    public static void main(String[] args) {

        try {

            // Class.forName("com.ibm.db2.jcc.DB2Driver");

            // String url =

            // "jdbc:derby:net://localhost:1527/address:user=libo;password=iamlibo;create=true:retrieveMessagesFromServerOnGetMessage=true;";

            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

            System.out.println("load driver success");

            String url = "jdbc:derby:/ddd;create=true;upgrade=true;";

            Connection con = DriverManager.getConnection(url);

            System.out.println("con is " + con);

            Statement stmt = con.createStatement();

            String sql ="SELECT * FROM app.groups";

            System.out.println(sql);

            ResultSet rs = stmt.executeQuery(sql);

            while (rs.next()) {

                System.out.print(rs.getInt(1) + ", ");

                System.out.println(rs.getString(2));

            }

            rs.close();

            stmt.close();

        } catch (ClassNotFoundException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch (SQLException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

这段代码很简单,只是建立一个连接,如果有表的就可以查询出来数据,但这里没有建立表。

参考了下面一篇:http://www.java3z.com/cwbwebhome/article/article2/1101.html?id=1152

这个例子是一个最小限度的JDBC 应用程序。 关于这个程序:

  • 以内嵌式模式(缺省的)或作为一个服务器环境中的客户端运行,这依赖于传递给程序的参数
  • 如果运行在内嵌式模式,则启动Derby 引擎
  • 如果运行在客户端模式,则连接到 Derby 网络服务器
  • 创建并连接到数据库
  • 创建一个表
  • 插入数据
  • 更新数据
  • 查询数据
  • 删除表
  • 关闭连接
  • 如果运行在内嵌式模式,则关闭 Derby。

以下是源码:

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.Properties;

/*

 * @author janet

 */

public class SimpleApp

{

    /* 缺省的模式是内嵌式的*/

    public String framework = "embedded";

    public String driver = "org.apache.derby.jdbc.EmbeddedDriver";

    public String protocol = "jdbc:derby:";

    public static void main(String[] args)

    {

        new SimpleApp().go(args);

    }

    void go(String[] args)

    {

        /* 处理参数,确定这个程序作为内嵌式使用还是作为客户端使用*/

        parseArguments(args);

        System.out.println("SimpleApp starting in " + framework + " mode.");

        try

        {

            /*

               装载驱动程序,如果是内嵌式模式,这将启动Derby, 因为它还没有运行.

             */

            Class.forName(driver).newInstance();

            System.out.println("Loaded the appropriate driver.");

            Connection conn = null;

            Properties props = new Properties();

            props.put("user", "user1");

            props.put("password", "user1");

            //create=true将创建数据库derbyDB

            conn = DriverManager.getConnection(protocol +"derbyDB;create=true", props);

            System.out.println("Connected to and created database derbyDB");

            conn.setAutoCommit(false);//设置自动提交模式

            Statement s = conn.createStatement();

            /*

               创建一个表,加入几条记录并更新一条.

             */

            s.execute("create table derbyDB(num int, addr varchar(40))");

            System.out.println("Created table derbyDB");

            s.execute("insert into derbyDB values (1956,'Webster St.')");

            System.out.println("Inserted 1956 Webster");

            s.execute("insert into derbyDB values (1910,'Union St.')");

            System.out.println("Inserted 1910 Union");

            s.execute(

                "update derbyDB set num=180, addr='Grand Ave.' where num=1956");

            System.out.println("Updated 1956 Webster to 180 Grand");

            s.execute(

                "update derbyDB set num=300, addr='Lakeshore Ave.' where num=180");

            System.out.println("Updated 180 Grand to 300 Lakeshore");

            /*

               查询并校验结果.

             */

            ResultSet rs = s.executeQuery(

                    "SELECT num, addr FROM derbyDB ORDER BY num");

            if (!rs.next())

            {

                throw new Exception("Wrong number of rows");

            }

            if (rs.getInt(1) != 300)

            {

                throw new Exception("Wrong row returned");

            }

            if (!rs.next())

            {

                throw new Exception("Wrong number of rows");

            }

            if (rs.getInt(1) != 1910)

            {

                throw new Exception("Wrong row returned");

            }

            if (rs.next())

            {

                throw new Exception("Wrong number of rows");

            }

            System.out.println("Verified the rows");

            s.execute("drop table derbyDB");//删除表

            System.out.println("Dropped table derbyDB");

 

            rs.close();

            s.close();

            System.out.println("Closed result set and statement");

            conn.commit();

            conn.close();

            System.out.println("Committed transaction and closed connection");

 

            boolean gotSQLExc = false;

            if (framework.equals("embedded"))

            {

                try

                {

                    DriverManager.getConnection("jdbc:derby:;shutdown=true");//关闭数据库服务

                }

                catch (SQLException se)

                {

                    gotSQLExc = true;

                }

                if (!gotSQLExc)

                {

                    System.out.println("Database did not shut down normally");

                }

                else

                {

                    System.out.println("Database shut down normally");

                }

            }

        }

        catch (Throwable e)

        {

            System.out.println("exception thrown:");

            if (e instanceof SQLException)

            {

                printSQLError((SQLException) e);

            }

            else

            {

                e.printStackTrace();

            }

        }

        System.out.println("SimpleApp finished");

    }

    static void printSQLError(SQLException e)

    {

        while (e != null)

        {

            System.out.println(e.toString());

            e = e.getNextException();

        }

    }

    private void parseArguments(String[] args)

    {


				
// System.setProperty("derby.system.home", "c:\\DBdata");//这样可以设置数据库数据的存放目录

int length = args.length;

        for (int index = 0; index < length; index++)

        {

            if (args[index].equalsIgnoreCase("jccjdbcclient"))

            {

                framework = "jccjdbc";

                driver = "com.ibm.db2.jcc.DB2Driver";

                protocol = "jdbc:derby:net://localhost:1527/";

            }

            if (args[index].equalsIgnoreCase("derbyclient"))

            {

                framework = "derbyclient";

                driver = "org.apache.derby.jdbc.ClientDriver";

                protocol = "jdbc:derby://localhost:1527/";

            }

        }

    }

}

下面是如何运行这个程序:

一、怎样在内嵌式环境(集成到桌面应用)中运行这个例子

我的工作目录是c:\java,先将derby.jar复制到c:\java\jar下。再写一个批处理文件run.bat,内容如下:

set CLASSPATH=c:\java\jar\derby.jar;%CLASSPATH%

打开windows XP的命令行窗口,转入工作目录。运行:


C:\java>run.bat
C:\java>set CLASSPATH=c:\java\jar\derby.jar;
C:\java>javac SimpleApp.java

C:\java>java SimpleApp
SimpleApp starting in embedded mode.
Loaded the appropriate driver.
Connected to and created database derbyDB
Created table derbyDB
Inserted 1956 Webster
Inserted 1910 Union
Updated 1956 Webster to 180 Grand
Updated 180 Grand to 300 Lakeshore
Verified the rows
Dropped table derbyDB
Closed result set and statement
Committed transaction and closed connection
Database shut down normally
SimpleApp finished

程序运行后将在当前目录下生成

  • derbyDB (目录)
    这个目录构成了 derbyDB 数据库目录. 你不能修改这个目录中的任何文件。
  • derbyDB\log (目录)
    这个目录保存了数据库的事务日志.
  • derbyDB\seg0 (目录)
    这个目录保存了数据库derbyDB的数据
  • derbyDB\service.properties
    一个内部文件,保存了一些配置参数
  • derby.LOG
    日志文件

二、 怎样在服务器环境中运行这个例子

(1)启动Derby Network Server

将derbynet.jar复制到c:\java\jar中,run.bat文件改为:
set CLASSPATH=c:\java\jar\derby.jar;c:\java\jar\derbynet.jar;%CLASSPATH%

新开一个DOS命令行窗口,在这个窗口中启动 Derby Network Server,如:

C:\java>run.bat

C:\java>set CLASSPATH=c:\java\jar\derby.jar;c:\java\jar\derbynet.jar;

C:\java>java org.apache.derby.drda.NetworkServerControl start
服务器准备在端口 1527 上接受连接。

(2)用 Derby 客户端模式运行这个程序:

将 derbyclient.jar 复制到c:\java\jar中,run.bat文件改为:
set CLASSPATH=c:\java\jar\derbyclient.jar;%CLASSPATH%

新开一个DOS命令行窗口,然后以Derby 客户端模式启动SimpleApp

C:\java>run.bat
C:\java>set CLASSPATH=c:\java\jar\derbyclient.jar;

C:\java>java SimpleApp derbyclient
SimpleApp starting in derbyclient mode.
Loaded the appropriate driver.
Connected to and created database derbyDB
Created table derbyDB
Inserted 1956 Webster
Inserted 1910 Union
Updated 1956 Webster to 180 Grand
Updated 180 Grand to 300 Lakeshore
Verified the rows
Dropped table derbyDB
Closed result set and statement
Committed transaction and closed connection
SimpleApp finished

(3)使用 IBM DB2 JDBC Universal Driver运行这个例子

      在Derby的10.0版本, IBM DB2 JDBC Universal Driver 是Derby Network Server唯一的客户端驱动.驱动程序需要从 IBM的站点下载 (IBM DB2 JDBC Universal Driver, for Apache Derby Network Server). 从10.1开始, Derby网络客户端驱动程序与Derby一起分发,并且是被推荐的客户端驱动程序,但 DB2 Universal Driver还被支持并且可以象下面一样被使用:

下载 db2jcc.jar和 db2jcc_license_c.jar,放到c:\java\jar目录下,run.bat的内容改为:
set CLASSPATH=c:\java\jar\db2jcc.jar;c:\java\jar\db2jcc_license_c.jar;%CLASSPATH%

C:\java>run.bat

C:\java>set CLASSPATH=c:\java\jar\db2jcc.jar;c:\java\jar\db2jcc_license_c.jarr;

c:\java>java SimpleApp jccjdbcclient

A successful run produces the following output:
SimpleApp starting in jccjdbc mode.
Loaded the appropriate driver.
Connected to and created database derbyDB
Created table derbyDB
Inserted 1956 Webster
Inserted 1910 Union
Updated 1956 Webster to 180 Grand
Updated 180 Grand to 300 Lakeshore
Verified the rows
Dropped table derbyDB
Closed result set and statement
Committed transaction and closed connection
SimpleApp finished

posted on 2007-04-07 15:28 Libo 阅读(1008) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: