Derby数据库有两种运行模式(Derby的jar包都在%JAVA_HOME%/db/lib)
一、嵌入式数据库
public class EmbeddedDerbyTester {
public static void main(String[] args) {
String driver = "org.apache.derby.jdbc.EmbeddedDriver";//在derby.jar里面
String dbName="EmbeddedDB";
String dbURL = "jdbc:derby:"+dbName+";create=true";//create=true表示当数据库不存在时就创建它
try {
Class.forName(driver);
Connection conn = DriverManager.getConnection(dbURL);//启动嵌入式数据库
Statement st = conn.createStatement();
st.execute("create table foo (FOOID INT NOT NULL,FOONAME VARCHAR(30) NOT NULL)");//创建foo表
st.executeUpdate("insert into foo(FOOID,FOONAME) values (1,'chinajash')");//插入一条数据
ResultSet rs = st.executeQuery("select * from foo");//读取刚插入的数据
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
System.out.println("id="+id+";name="+name);
}
} catch(Exception e){
e.printStackTrace();
}
}
}
运行上面程序后,会在当前目录生成名为EmbeddedDB的文件夹,既是EmbeddedDB数据库的数据文件存放的地方,控制台将输出
id=1;name=chinajash
二、网络数据库
public class NetworkServerDerbyTester {
public static void main(String[] args) {
String driver = "org.apache.derby.jdbc.ClientDriver";//在derbyclient.jar里面
String dbName="NetworkDB";
String connectionURL = "jdbc:derby://localhost:1527/" + dbName + ";create=true";
try {
/*
创建Derby网络服务器,默认端口是1527,也可以通过运行
<Derby_Home>/frameworks/NetworkServer/bin/startNetworkServer.bat
来创建并启动Derby网络服务器,如果是Unix,用startNetworkServer.ksh
*/
NetworkServerControl derbyServer = new NetworkServerControl();//NetworkServerControl类在derbynet.jar里面
PrintWriter pw = new PrintWriter(System.out);//用系统输出作为Derby数据库的输出
derbyServer.start(pw);//启动Derby服务器
Class.forName(driver);
DriverManager.getConnection(connectionURL);
//do something
derbyServer.shutdown();//关闭Derby服务器
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
运行上面程序后,会在当前目录生成名为NetworkDB的文件夹