background image

named helloDB

conn=DriverManager.getConnection("jdbc:derby:helloDB;create=true

", props); 

System.out.println("create and connect to helloDB");
 conn.setAutoCommit(false); // create a table and insert two records 

Statement s = conn.createStatement(); 
s.execute("create table hellotable(name varchar(40), score int)"); 
System.out.println("Created page 1 table hellotable");
 s.execute("insert into hellotable values('Ruth Cao', 86)"); 
s.execute("insert into hellotable values ('Flora Shi', 92)"); // list the 
two records ResultSet rs = s.executeQuery( "SELECT name, score 
FROM hellotable ORDER BY score"); 
System.out.println("name\t\tscore");
while(rs.next()) {

StringBuilder builder = new StringBuilder(rs.getString(1)); 
builder.append("\t");
builder.append(rs.getInt(2)); 
System.out.println(builder.toString()); }

 // delete the table

 s.execute("drop table hellotable");

 System.out.println("Dropped table hellotable");
 rs.close(); 

s.close(); 
System.out.println("Closed result set and statement"); 
conn.commit(); 
conn.close(); 

System.out.println("Committed   transaction   and   closed 

connection");

 try{ // perform a clean shutdown 

DriverManager.getConnection("jdbc:derby:;shutdown=true"); }

 catch (SQLException se) {

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

(Throwable e) { // handle the exception } 

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

 

 

随后,我们在命令行 (本例为 Windows 

 

 

平台, 当然, 其它系统下稍作改动

 

即可) 下键入以下命令:

 

清单 2. 

 

运行 HelloJavaDB 

 

命令 java –cp .;%JAVA_HOME%\db\lib\derby.jar HelloJavaDB

 

程序将会按照我们预想的那样执行,图 1 是执行结果的一部分截屏:

 

图 1. HelloJavaDB 程序的执行结果

 

上述的程序和以往没什么区别。不同的是我们不需要再为 DBMS 

 

的配置而劳神,因为 Derby 

 

已经自动地在当前目录下新建了一个名为 helloDB 的目录,来物理地存储数据和日志。需要做
的 只 是 注 意 命 名 问 题 : 在 内 嵌 模 式 下 驱 动 的 名 字 应 为