学习使用Java DataBase
在前几天,转贴了java网站上一篇介绍使用Java DB的文章,http://blog.matrix.org.cn/page/icess?entry=using_java_db_in_desktop 里面介绍了如何在桌面程序中使用java DB,今天使用了一下感觉很不错.
但上面那篇文章中,是通过一个桌面程序来介绍java DB的,看的时候可能会感到比较混乱,今天我就按照他的例子,从中拿出 介绍java db的代码, 来看看如何使用它吧!
在看如何使用java db以前,先看看java db 是什么, 有什么特点.
What's Java DB?
要使用Java DB, 就不免想问起什么是java db, 其实java db就是在ibm 捐赠给Apache开源项目组的一个用java实现的轻量级嵌入式数据库代码基础上发展起来的. sun Java DB主页的描述如下:
Java DB is Sun's supported distribution of the open source Apache Derby 100% Java technology database. It is fully transactional, secure, easy-to-use, standards-based -- SQL, JDBC API, and Java EE -- yet small, only 2MB. The Apache Derby project has a strong and growing community that includes developers from large companies such as Sun Microsystems and IBM as well as individual contributors.
Apache Derby 项目主页:http://db.apache.org/derby/
Java DB主页: http://developers.sun.com/prodtech/javadb/
Java DB 的特性以及优点:
Features & Benefits
Sun Java DB is based on the open source Apache Derby project. It provides a full-featured, robust, small-footprint Java database management system that is cost effective and simple to deploy.
Pure Java
Java DB is written in Java to take advantage of Java's write once, run anywhere promise. Java DB supports J2SE, J2EE and J2ME standards.
Standards- based
Java DB technology adheres to database standards such as JDBC and ANSI SQL standards. This means Java DB provides the functionality expected of a sophisticated relational database, including SQL syntax, transaction management, concurrency, triggers, and backups. It also means that it is easy to upgrade an application using Java DB to other standards-based databases, such as Oracle and DB2.
Easy to use
Java DB is easy to use and requires zero-administration. This eliminates the need for a database administrator.
Application-embedded or client-server mode
The flexibility to support both embedded and client-server mode allows Java DB to adapt to diverse deployment scenarios. In embedded mode, Java DB runs on the same JVM as the application and users may not even be aware that they are accessing a relational database.
Secure
Java DB provides a numbers of security mechanisms including database file encryption, authentication through either external LDAP directory or built-in repository, and authorization. In addition, access to the database can also be controlled at read-only or read-write level.
Sophisticated – with triggers and stored procedures
Java DB allows users to define trigger to ensure referential integrity. It also supports Java stored procedures.
Small foot-print
With a foot-print of 2MB, Java DB is a perfect fit for desktop applications, mobile solutions and small devices that require a full featured, robust database.
Cost-effective
Java DB is available for free under the Apache license and requires no administration if embedded and little if used in client-server mode.
Full support from Sun
Sun offers full, 24 x 7 support for Java DB.
可以看出Java DB的优点还是很多的.以后在sun 的软件中都带有Java DB了.
下面来看看如何使用Java DB吧.
嵌入式数据库和一般的数据库不同,在使用以前,需要指定一个存放数据的目录和指定数据库的配置文件.
配置文件可以很简单:不用解释了 如下:
# Sample ResourceBundle properties file
user=
addressuserpassword=
addressuserderby.driver=
org.apache.derby.jdbc.EmbeddedDriverderby.url=
jdbc:derby:db.table=
ADDRESSdb.schema=
APP当然了 以上配置信息,也可以用一个Property 属性对象来构造,然后在得到数据库连接的时候把该对象传递进去也是可以的. 不过使用配置文件是为了方便修改相关配置信息而设定的.
通过如下方法来设置 数据库数据的存放目录:
private void setDBSystemDir() {
// decide on the db system directory
//String userHomeDir = System.getProperty("user.home", ".");
String userHomeDir = System.getProperty("user.dir", ".");
String systemDir = userHomeDir + "/.addressbook";
System.setProperty("derby.system.home", systemDir);
// create the db system directory
File fileSystemDir = new File(systemDir);
fileSystemDir.mkdir();
}
然后就是加载数据库驱动了, Java DB的数据库驱动是集成在一起的,也是通过 Class.forName() 的方式加载的,内嵌的驱动名字是
org.apache.derby.jdbc.EmbeddedDriver 本例子中使用下面的方法加载驱动.
private void loadDatabaseDriver(String driverName) {
// load Derby driver
try {
Class.forName(driverName);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
这样,加载了驱动以后,只有得到Connection就可以操作数据了.
在操作数据以前,我们先建立一个 数据表, 使用的sql 语句如下:
private static final String strCreateAddressTable =
"create table APP.ADDRESS (" +
" ID INTEGER NOT NULL PRIMARY KEY GENERATED
ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)," +
" LASTNAME VARCHAR(30), " +
" FIRSTNAME VARCHAR(30), " +
" MIDDLENAME VARCHAR(30), " +
" PHONE VARCHAR(20), " +
" EMAIL VARCHAR(30), " +
" ADDRESS1 VARCHAR(30), " +
" ADDRESS2 VARCHAR(30), " +
" CITY VARCHAR(30), " +
" STATE VARCHAR(30), " +
" POSTALCODE VARCHAR(20), " +
" COUNTRY VARCHAR(30) " +
")";
然后使用如下方法来建立数据库和数据表:
private boolean createTables(Connection dbConnection) {
boolean bCreatedTables = false;
Statement statement = null;
try {
statement = dbConnection.createStatement();
// 创建表格...
statement.execute(strCreateAddressTable);
bCreatedTables = true;
} catch (SQLException ex) {
ex.printStackTrace();
}
return bCreatedTables;
}
private boolean createDatabase() {
boolean bCreated = false;
Connection dbConnection = null;
String dbUrl = getDatabaseUrl();
dbProperties.put("create", "true");
try {
dbConnection = DriverManager.getConnection(dbUrl, dbProperties);
bCreated = createTables(dbConnection);
} catch (SQLException ex) {
}
dbProperties.remove("create");
return bCreated;
}
由于是嵌入式数据库,创建表格也要编程来实现,当然也有和IDE配合使用的插件可以使用.
在创建数据库和表时, 需要指定 一个create 属性为true, 就象上面的那样, 同样,在断开连接 关闭数据库时,我们也要指定属性 用编程的方法来关闭数据库, 这是和普通数据库不同的地方. 下面是关闭数据库的代码:
public void disconnect() {
if(isConnected) {
String dbUrl = getDatabaseUrl();
dbProperties.put("shutdown", "true");
try {
DriverManager.getConnection(dbUrl, dbProperties);
} catch (SQLException ex) {
}
isConnected = false;
}
}
然后我们就可以通过得到Connection 象操作普通数据库一样来操作Java DB了. 如下:
dbConnection = DriverManager.getConnection(dbUrl, dbProperties);
stmtSaveNewRecord = dbConnection.prepareStatement(strSaveAddress, Statement.RETURN_GENERATED_KEYS);
性能如何呢: 经过我的测试 插入 100 行(每行有11个字符串) 数据 要2100 多毫秒. 取出100 行需要 1500多毫秒 不知道大家认为如何.
本文用到的全部代码: 可以在此出下载: http://icess.my.china.com/downloads/index.htm