Derby并不是一个新的数据库产品,它是由IBM捐献给Apache的DB项目的一个纯Java数据库,JDK6.0里面带的这个Derby的版本是10.2.1.7,支持存储过程和触发器;有两种运行模式,一种是作为嵌入式数据库,另一种是作为网络数据库,前者的数据库服务器和客户端都在同一个JVM里面运行,后者允许数据库服务器端和客户端不在同一个JVM里面,而且允许这两者在不同的物理机器上.值得注意的是JDK6里面的这个Derby支持JDK6的新特性JDBC 4.0规范(JSR 221),现在我们如果要练习JDBC的用法,没有必要单独装一个数据库产品了,直接用Derby就行.

下面是个使用derby的简单例子:

首先导入JAR包:derby.jar,如果你装的是JDK6,在C:/Program Files/Sun/JavaDB/lib目录下就可以找到.

然后就要创建数据库了:

Java代码

privateConnection getConnection()throwsSQLException {

Connection connection = DriverManager

.getConnection("jdbc:derby:userDB;create=true;user=test;password=test");

connection.setAutoCommit(false);

returnconnection;

}

private Connection getConnection() throws SQLException {

Connection connection = DriverManager

.getConnection("jdbc:derby:userDB;create=true;user=test;password=test");

connection.setAutoCommit(false);

return connection;

}

其中

userDB是要连接数据库的名字,

create=true表示如果该数据库不存在,则创建该数据库,如果数据库存在,则用用户user=test;密码password=test连接数据库.

有了数据库,接下来该建表了:

Java代码

privatevoidcreateTable(Connection connection)throwsSQLException {

Statement statement = connection.createStatement();

String sql ="create table USERS("

+"   ID                           BIGINT                       not null generated by default as identity,"

+"   USER_NAME            VARCHAR(20)            not null,"

+"   PASSWORD             VARCHAR(20),"

+"   constraint P_KEY_1 primary key (ID))";

statement.execute(sql);

sql ="create unique index USER_NAME_INDEX on USERS ("

+"   USER_NAME            ASC)";

statement.execute(sql);

statement.close();

}

private void createTable(Connection connection) throws SQLException {

Statement statement = connection.createStatement();

String sql = "create table USERS("

+ " ID BIGINT not null generated by default as identity,"

+ " USER_NAME VARCHAR(20) not null,"

+ " PASSWORD VARCHAR(20),"

+ " constraint P_KEY_1 primary key (ID))";

statement.execute(sql);

sql = "create unique index USER_NAME_INDEX on USERS ("

+ " USER_NAME ASC)";

statement.execute(sql);

statement.close();

}

创建了

USERS表,包括

ID,USER_NAME,PASSWORD三个列,其中ID是主键,其中

generated by default as identity的作用类似sequence,

identity是定义自动加一的列,

GENERATED BY ALWAYS AS IDENTITY

GENERATED BY DEFAULT AS IDENTITY

By always和by default是说明生成这个IDENTITY的方式。

By always是完全由系统自动生成。

by default是可以由用户来指定一个值。

编写与USERS表对应的javabean(这个就不多说了),:

Java代码

publicclassUserimplementsSerializable {

/**

*

*/

privatestaticfinallongserialVersionUID = 1L;

privateLong id;

privateString userName;

privateString password;

publicLong getId() {

returnid;

}

publicvoidsetId(Long id) {

this.id = id;

}

publicString getUserName() {

returnuserName;

}

publicvoidsetUserName(String userName) {

this.userName = userName;

}

publicString getPassword() {

returnpassword;

}

publicvoidsetPassword(String password) {

this.password = password;

}

}

public class User implements Serializable {

/**

*

*/

private static final long serialVersionUID = 1L;

private Long id;

private String userName;

private String password;

public Long getId() {

return id;

}

public void setId(Long id) {

this.id = id;

}

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

}

接下来就可以就数据库进行增删改查的操作了:

插入数据:

Java代码

privatevoidcreate(User user) {

Connection connection =null;

try{

connection =this.getConnection();

PreparedStatement statement = connection

.prepareStatement("insert into users (user_name,password) values(?,?)");

intindex =1;

statement.setString(index++, user.getUserName());

statement.setString(index++, user.getPassword());

statement.execute();

user.setId(this.getId(connection));

connection.commit();

}catch(SQLException e) {

rollback(connection);

thrownewRuntimeException(e);

}finally{

if(connection !=null) {

close(connection);

}

}

}

private void create(User user) {

Connection connection = null;

try {

connection = this.getConnection();

PreparedStatement statement = connection

.prepareStatement("insert into users (user_name,password) values(?,?)");

int index = 1;

statement.setString(index++, user.getUserName());

statement.setString(index++, user.getPassword());

statement.execute();

user.setId(this.getId(connection));

connection.commit();

} catch (SQLException e) {

rollback(connection);

throw new RuntimeException(e);

} finally {

if (connection != null) {

close(connection);

}

}

}

Java代码

privateLong getId(Connection connection)throwsSQLException {

CallableStatement callableStatement = connection

.prepareCall("values identity_val_local()");

ResultSet resultSet = callableStatement.executeQuery();

resultSet.next();

Long id = resultSet.getLong(1);

resultSet.close();

callableStatement.close();

returnid;

}

private Long getId(Connection connection) throws SQLException {

CallableStatement callableStatement = connection

.prepareCall("values identity_val_local()");

ResultSet resultSet = callableStatement.executeQuery();

resultSet.next();

Long id = resultSet.getLong(1);

resultSet.close();

callableStatement.close();

return id;

}

getId方法是获得系统默认的id值,是通过identity_val_local()获得的,而函数IDENTITY_VAL_LOCAL()则可以在INSERT语句执行之后,为我们返回刚才系统为id所产生的值.感觉还是有点想sequence的curr_val.

修改数据:

Java代码

privatevoidupdate(User user) {

Connection connection =null;

try{

connection =this.getConnection();

PreparedStatement statement = connection

.prepareStatement("update users set user_name=?,password=? where id=?");

intindex =1;

statement.setString(index++, user.getUserName());

statement.setString(index++, user.getPassword());

statement.setLong(index++, user.getId());

statement.execute();

connection.commit();

}catch(SQLException e) {

rollback(connection);

thrownewRuntimeException(e);

}finally{

if(connection !=null) {

close(connection);

}

}

}

private void update(User user) {

Connection connection = null;

try {

connection = this.getConnection();

PreparedStatement statement = connection

.prepareStatement("update users set user_name=?,password=? where id=?");

int index = 1;

statement.setString(index++, user.getUserName());

statement.setString(index++, user.getPassword());

statement.setLong(index++, user.getId());

statement.execute();

connection.commit();

} catch (SQLException e) {

rollback(connection);

throw new RuntimeException(e);

} finally {

if (connection != null) {

close(connection);

}

}

}

删除数据:

Java代码

publicvoiddelete(Long id) {

Connection connection =null;

try{

connection =this.getConnection();

PreparedStatement statement = connection

.prepareStatement("delete from users where id=?");

statement.setLong(1, id);

statement.execute();

connection.commit();

}catch(SQLException e) {

rollback(connection);

thrownewRuntimeException(e);

}finally{

if(connection !=null) {

close(connection);

}

}

}

public void delete(Long id) {

Connection connection = null;

try {

connection = this.getConnection();

PreparedStatement statement = connection

.prepareStatement("delete from users where id=?");

statement.setLong(1, id);

statement.execute();

connection.commit();

} catch (SQLException e) {

rollback(connection);

throw new RuntimeException(e);

} finally {

if (connection != null) {

close(connection);

}

}

}

查询数据:

Java代码

publicUser findById(Long id) {

Connection connection =null;

try{

connection =this.getConnection();

PreparedStatement statement = connection

.prepareStatement("select user_name,password from users where id=?");

statement.setLong(1, id);

ResultSet resultSet = statement.executeQuery();

User user =null;

if(resultSet.next()) {

user =newUser();

user.setId(id);

user.setUserName(resultSet.getString("user_name"));

user.setPassword(resultSet.getString("password"));

}

resultSet.close();

statement.close();

connection.commit();

returnuser;

}catch(SQLException e) {

thrownewRuntimeException(e);

}finally{

if(connection !=null) {

close(connection);

}

}

}

public User findById(Long id) {

Connection connection = null;

try {

connection = this.getConnection();

PreparedStatement statement = connection

.prepareStatement("select user_name,password from users where id=?");

statement.setLong(1, id);

ResultSet resultSet = statement.executeQuery();

User user = null;

if (resultSet.next()) {

user = new User();

user.setId(id);

user.setUserName(resultSet.getString("user_name"));

user.setPassword(resultSet.getString("password"));

}

resultSet.close();

statement.close();

connection.commit();

return user;

} catch (SQLException e) {

throw new RuntimeException(e);

} finally {

if (connection != null) {

close(connection);

}

}

}

以上就是derby的简单操作.

java db 使用_JavaDB的基本使用相关推荐

  1. Java SE 6 新特性: Java DB 和 JDBC 4.0

    http://www.ibm.com/developerworks/cn/java/j-lo-jse65/index.html 长久以来,由于大量(甚至几乎所有)的 Java 应用都依赖于数据库,如何 ...

  2. Java DB中的Java用户定义类型(UDT)

    Java DB是基于Java编程语言和SQL的关系数据库管理系统. 这是Apache软件基金会的开源Derby项目的Oracle版本. Java SE 7 SDK中包含Java DB. 用户定义类型( ...

  3. Java DB中的Java存储过程

    1 Java存储过程 这篇文章是关于Java DB中的Java存储过程的. Java DB是基于Java编程语言和SQL的关系数据库管理系统. 这是Apache软件基金会的开源Derby项目的Orac ...

  4. Java DB嵌入式模式

    Java DB是基于Java编程语言和SQL的关系数据库管理系统. 这是Apache软件基金会的开源Derby项目的Oracle版本. Java SE 7 SDK中包含Java DB. Java DB ...

  5. 在桌面应用中使用JAVA DB[组图]

    原文地址:http://Java.sun.com/developer/technicalArticles/J2SE/Desktop/javadb/ 原作者:John O'Conner 日期:2006- ...

  6. 4.Java数据库连接_1.JDBC (Java DB Connection)简介

    //============================================================================ Mysql安装参考: http://blo ...

  7. JDBC (Java DB Connection)---Java数据库连接

    一:JDBC (Java DB Connection)-Java数据库连接 JDBC是一种可用于执行SQL语句的JAVA API(ApplicationProgramming Interface应用程 ...

  8. java的netbeans数据库,使用 Java DB (Derby) 数据库

    使用 Java DB (Derby) 数据库 This tutorial needs a review. You can open a JIRA issue, or edit it in GitHub ...

  9. 使用 Java DB (Derby) 数据库

    使用 Java DB (Derby) 数据库 https://netbeans.org/kb/docs/ide/java-db_zh_CN.html 本文档说明了如何在 NetBeans IDE 中设 ...

最新文章

  1. 未捕获ReferenceError:未定义$?
  2. 【项目实战】vue+springboot项目使用富文本编辑器实现长文章发表和展示
  3. cos66度20分怎么用计算机算,物化2期末考试计算复习题
  4. 使用 keytool 生成安卓应用程序签名
  5. 机器学习算法分类总结
  6. python四舍五入round_四舍五入就用round( )?Python四舍五入的正确打开方式!-Go语言中文社区...
  7. hadoop-执行mapreduce时主机名非法的处理
  8. 夏昕的3部开发手册.- -
  9. 迷宫算法,求解所有路径(DFS),(bug找了好久 )
  10. 从零开始写一个武侠冒险游戏-1-状态原型
  11. Arduino安全和警报系统项目
  12. 有关于fprintf()函数的用法
  13. Google退出内地市场
  14. cairo和pixman库给bmp图片加文字水印
  15. uninstall和install
  16. pandas:世界各国GDP数据集数据清洗案例
  17. Linux操作系统 第六章
  18. 印光法师:《灵岩遗旨》壹、悲化有情
  19. 【它山之玉】研究生回复审稿意见的门道---科学网马臻
  20. linux 是否支持中文

热门文章

  1. php环境informix,在Nginx + php-fpm(fastcgi)环境下配置informix的连接
  2. 2017.9.23 循环格 思考记录
  3. 【英语学习】【Level 07】U04 Rest and Relaxation L6 Your home away from home
  4. 【英语学习】【Daily English】U03 Leisure Time L04 I need to squeeze in some time for reading
  5. mysql数据库 二十一练习题 及答案 (mysql练习题)
  6. 2.2基本算法之递归和自调用函数_用栈算法递归解决汉诺塔问题
  7. centos6.0安装中文输入法
  8. 分形:MandelBrot和Julia
  9. 100层楼扔2个鸡蛋、3个鸡蛋……
  10. vant部署_详解VUE项目中安装和使用vant组件