关于Derby使用的基本说明
1.特点优势
- Java based, Free software, Open source, Apache license version 2.0
- 全功能RDBMS
- 可嵌入式运行,占用资源少
- 轻量级的持久化文件,平台无关
2.概念与实践
2.1 嵌入式与多用户访问
这里所谓的“嵌入式”是指:Derby提供了一种可行性,使得应用级程序中可以很方便地启动一个数据库引擎模块,提供数据库功能服务。如此一来,应用与数据库就不再是传统的分布式关系,而变成了嵌入关系。技术上讲,数据库不再是一个独立的进程,而是存在并受控于应用的进程中。
Derby是一款java程序,使用它的方式其实就是使用其提供的jar。
简单地用Derby作为嵌入式数据库使用,仅需使用derby.jar
即可。derby.jar
中包括一个数据库引擎和一个嵌入式的JDBC驱动(进程内通信的JDBC Driver)。应用使用这个驱动与内嵌于自身进程的数据库引擎交互即可。org.apache.derby.jdbc.EmbeddedDriver
是该驱动的名称。
以下是连接到内嵌数据库的标准方式:
Connection conn = DriverManager.getConnection("jdbc:derby:sample");
那么数据库是什么时候启动的呢?当第一次连接创建的时候。最简单的一个样例程序如下所示:
public class SimpleApp
{
private String protocol = "jdbc:derby:";
public static void main(String[] args)
{
new SimpleApp().go(args);
System.out.println("SimpleApp finished");
}
void go(String[] args)
{
System.out.println("SimpleApp starting in " + framework + " mode");
/* We will be using Statement and PreparedStatement objects for
* executing SQL. These objects, as well as Connections and ResultSets,
* are resources that should be released explicitly after use, hence
* the try-catch-finally pattern used below.
* We are storing the Statement and Prepared statement object references
* in an array list for convenience.
*/
Connection conn = null;
ArrayList<Statement> statements = new ArrayList<Statement>(); // list of Statements, PreparedStatements
PreparedStatement psInsert;
PreparedStatement psUpdate;
Statement s;
ResultSet rs = null;
try
{
Properties props = new Properties(); // connection properties
// providing a user name and password is optional in the embedded
// and derbyclient frameworks
props.put("user", "user1");
props.put("password", "user1");
/* By default, the schema APP will be used when no username is
* provided.
* Otherwise, the schema name is the same as the user name (in this
* case "user1" or USER1.)
*
* Note that user authentication is off by default, meaning that any
* user can connect to your database using any password. To enable
* authentication, see the Derby Developer's Guide.
*/
String dbName = "derbyDB"; // the name of the database
/*
* This connection specifies create=true in the connection URL to
* cause the database to be created when connecting for the first
* time. To remove the database, remove the directory derbyDB (the
* same as the database name) and its contents.
*
* The directory derbyDB will be created under the directory that
* the system property derby.system.home points to, or the current
* directory (user.dir) if derby.system.home is not set.
*/
conn = DriverManager.getConnection(protocol + dbName
+ ";create=true", props);
System.out.println("Connected to and created database " + dbName);
// We want to control transactions manually. Autocommit is on by
// default in JDBC.
conn.setAutoCommit(false);
/* Creating a statement object that we can u