将derby最基本的安装到您的应用程序中非常轻松。这只是将库/ jar放在类路径上的问题。 Netbeans已经附带了这个库,因此您无需下载它。如果出于任何原因,它没有,您可以从here下载。解压缩后,只需将derby.jar(以及其他必要的话)添加到类路径中。
基本上来自Netbeans,从您的项目中,右键单击[Library]并选择[Add Library]。
然后只需选择[Java DB]库
如果你下载了库,那么选择[Add Jar],而不是[Add Library],然后搜索你下载它的jar。
这些是Netbeans库附带的罐子
然后您可以在应用程序中使用该数据库。嵌入式版本在与应用程序相同的JVM上运行,因此您可能需要自己负责启动和关闭数据库。这是一个示例应用程序,它启动了 - 创建了db-inserts-choices-shutsdown。
import java.sql.*;
public class DerbyProject {
public static void main(String[] args) throws Exception {
/* ------- Start DB ----------- */
final String driver = "org.apache.derby.jdbc.EmbeddedDriver";
Class.forName(driver).newInstance();
final String protocol = "jdbc:derby:";
final String dbName = "derbyDB";
Connection connection = DriverManager.getConnection(
protocol + dbName + ";create=true");
System.out.println("===== Started/Connected DB =====");
/*
* Drop table for testing. If we don't drop, running the
* same program will fail, if we start our application over
* as the new table has been persisted
*/
final String dropSql = "drop table users";
Statement statement = connection.createStatement();
try {
statement.execute(dropSql);
System.out.println("===== Dropped Table 'users' =====");
} catch (SQLException e) {
if (!e.getSQLState().equals("42Y55")) {
throw e;
}
}
/* ----- Creeate 'users' table ----- */
final String createSql = "create table users ( id int, name varchar(32) )";
statement.execute(createSql);
System.out.println("===== Created Table 'users' =====");
/* ----- Insert 'peeskillet' into 'users' ----*/
final String insertSql = "insert into users values ( 1 , 'peeskillet' )";
statement.execute(insertSql);
System.out.println("===== inserted 'peeskillet into 'users' =====");
/* ----- Select from 'users' table ----- */
final String selectSql = "select name from users where id = 1";
ResultSet rs = statement.executeQuery(selectSql);
if (rs.next()) {
System.out.println("===== Selected from 'users' with id 1 \n"
+ "\t\t\t result: " + rs.getString("name") + " =====");
}
/* ------ Shut Down DB ------- */
try {
DriverManager.getConnection("jdbc:derby:;shutdown=true");
} catch (SQLException se) {
if (((se.getErrorCode() == 50000)
&& ("XJ015".equals(se.getSQLState())))) {
System.out.println("Derby shut down normally");
} else {
System.err.println("Derby did not shut down normally");
throw se;
}
}
statement.close();
rs.close();
connection.close();
}
}
当我们构建它时,Netbeans默认构建应该将jar放入dist\lib并将这些jar放在MANIFEST.MF的类路径中。您可以从命令行运行jar来测试它
如果您打开Netbeans中的文件视图,您可以看到数据的实际存储位置。
有关Derby和Derby教程的更多信息: