🎶 Sym - 一款用 Java 实现的现代化社区(论坛/BBS/社交网络/博客)平台

📕 思源笔记 - 一款桌面端笔记应用,支持 Windows、Mac 和 Linux

🎸 Solo - B3log 分布式社区的博客端节点,欢迎加入下一代社区网络

♏ Vditor - 一款浏览器端的 Markdown 编辑器

javaDB—— derby 简单操作

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

Java代码 复制代码

  1. private Connection getConnection() throws SQLException {   
  2.         Connection connection = DriverManager   
  3.                 .getConnection("jdbc:derby:userDB;create=true;user=test;password=test");   
  4.         connection.setAutoCommit(false);   
  5.         return connection;   
  6.     }  

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代码 复制代码

  1. private void createTable(Connection connection) throws SQLException {   
  2.     Statement statement = connection.createStatement();   
  3.   
  4.     String sql = "create table USERS("  
  5.             + "   ID                           BIGINT                       not null generated by default as identity,"  
  6.             + "   USER_NAME            VARCHAR(20)            not null,"  
  7.             + "   PASSWORD             VARCHAR(20),"  
  8.             + "   constraint P_KEY_1 primary key (ID))";   
  9.     statement.execute(sql);   
  10.   
  11.     sql = "create unique index USER_NAME_INDEX on USERS ("  
  12.             + "   USER_NAME            ASC)";   
  13.     statement.execute(sql);   
  14.   
  15.     statement.close();   
  16. }  

 

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代码 复制代码

  1. public class User implements Serializable {   
  2.   
  3.     /**  
  4.      *   
  5.      */  
  6.     private static final long serialVersionUID = 1L;   
  7.   
  8.     private Long id;   
  9.   
  10.     private String userName;   
  11.   
  12.     private String password;   
  13.   
  14.     public Long getId() {   
  15.         return id;   
  16.     }   
  17.   
  18.     public void setId(Long id) {   
  19.         this.id = id;   
  20.     }   
  21.   
  22.     public String getUserName() {   
  23.         return userName;   
  24.     }   
  25.   
  26.     public void setUserName(String userName) {   
  27.         this.userName = userName;   
  28.     }   
  29.   
  30.     public String getPassword() {   
  31.         return password;   
  32.     }   
  33.   
  34.     public void setPassword(String password) {   
  35.         this.password = password;   
  36.     }   
  37. }  

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代码 复制代码

  1. private void create(User user) {   
  2.         Connection connection = null;   
  3.   
  4.         try {   
  5.             connection = this.getConnection();   
  6.             PreparedStatement statement = connection   
  7.                     .prepareStatement("insert into users (user_name,password) values(?,?)");   
  8.   
  9.             int index = 1;   
  10.             statement.setString(index++, user.getUserName());   
  11.             statement.setString(index++, user.getPassword());   
  12.   
  13.             statement.execute();   
  14.   
  15.             user.setId(this.getId(connection));   
  16.   
  17.             connection.commit();   
  18.         } catch (SQLException e) {   
  19.             rollback(connection);   
  20.             throw new RuntimeException(e);   
  21.         } finally {   
  22.             if (connection != null) {   
  23.                 close(connection);   
  24.             }   
  25.         }   
  26.     }  

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代码 复制代码

  1. private Long getId(Connection connection) throws SQLException {   
  2.     CallableStatement callableStatement = connection   
  3.             .prepareCall("values identity_val_local()");   
  4.   
  5.     ResultSet resultSet = callableStatement.executeQuery();   
  6.     resultSet.next();   
  7.     Long id = resultSet.getLong(1);   
  8.     resultSet.close();   
  9.     callableStatement.close();   
  10.     return id;   
  11. }  

 

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所产生的值.感觉还是有点想sequencecurr_val.


修改数据:

Java代码 复制代码

  1.   
  2. private void update(User user) {   
  3.         Connection connection = null;   
  4.   
  5.         try {   
  6.             connection = this.getConnection();   
  7.             PreparedStatement statement = connection   
  8.                     .prepareStatement("update users set user_name=?,password=? where id=?");   
  9.   
  10.             int index = 1;   
  11.             statement.setString(index++, user.getUserName());   
  12.             statement.setString(index++, user.getPassword());   
  13.             statement.setLong(index++, user.getId());   
  14.   
  15.             statement.execute();   
  16.   
  17.             connection.commit();   
  18.         } catch (SQLException e) {   
  19.             rollback(connection);   
  20.             throw new RuntimeException(e);   
  21.         } finally {   
  22.             if (connection != null) {   
  23.                 close(connection);   
  24.             }   
  25.         }   
  26.     }  

 

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代码 复制代码

  1.   
  2. public void delete(Long id) {   
  3.         Connection connection = null;   
  4.   
  5.         try {   
  6.             connection = this.getConnection();   
  7.             PreparedStatement statement = connection   
  8.                     .prepareStatement("delete from users where id=?");   
  9.             statement.setLong(1, id);   
  10.             statement.execute();   
  11.             connection.commit();   
  12.         } catch (SQLException e) {   
  13.             rollback(connection);   
  14.             throw new RuntimeException(e);   
  15.         } finally {   
  16.             if (connection != null) {   
  17.                 close(connection);   
  18.             }   
  19.         }   
  20.     }  

 

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代码 复制代码

  1. public User findById(Long id) {   
  2.     Connection connection = null;   
  3.   
  4.     try {   
  5.         connection = this.getConnection();   
  6.   
  7.         PreparedStatement statement = connection   
  8.                 .prepareStatement("select user_name,password from users where id=?");   
  9.         statement.setLong(1, id);   
  10.         ResultSet resultSet = statement.executeQuery();   
  11.   
  12.         User user = null;   
  13.   
  14.         if (resultSet.next()) {   
  15.             user = new User();   
  16.             user.setId(id);   
  17.             user.setUserName(resultSet.getString("user_name"));   
  18.             user.setPassword(resultSet.getString("password"));   
  19.         }   
  20.   
  21.         resultSet.close();   
  22.         statement.close();   
  23.         connection.commit();   
  24.         return user;   
  25.     } catch (SQLException e) {   
  26.         throw new RuntimeException(e);   
  27.     } finally {   
  28.         if (connection != null) {   
  29.             close(connection);   
  30.         }   
  31.     }   
  32. }  

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的简单操作.


欢迎注册黑客派社区,开启你的博客之旅。让学习和分享成为一种习惯!

留下你的脚步