Derby is not a new database product. It is a pure Java Database donated by IBM to the Apache dB project. The Derby version included in jdk6.0 is 10.2.1.7, supports stored procedures and triggers. There are two operating modes: embedded database and network database, the former database server and client are both running in the same JVM, and the latter allows the database server and client to be not in the same JVM, and the two are allowed on different physical machines. it is worth noting that the Derby in JDK 6 supports the jdk6 new JDBC 4.0 specification (JSR 221). Now, if we want to practice JDBC usage, there is no need to install a database product separately, use Derby directly.
Here is a simple example of using Derby:
First, import the jar package: Derby. Jar. If you have installed JDK 6, you can find it in the C:/program files/Sun/javadb/lib directory.
Create a database:
Java code
- Private connection getconnection () throws sqlexception {
- Connection connection = drivermanager
- . Getconnection ("JDBC: Derby: userdb; Create = true; user = test; Password = test ");
- Connection. setautocommit (false );
- Return connection;
- }
private Connection getConnection() throws SQLException {Connection connection = DriverManager.getConnection("jdbc:derby:userDB;create=true;user=test;password=test");connection.setAutoCommit(false);return connection;}
Userdb is the name of the database to be connected, and create = true indicates that the database is created if the database does not exist. If the database exists, the user = test is used; password = test to connect to the database.
With the database, we should create the table:
Java code
- Private void createtable (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.exe cute (SQL );
- SQL = "create unique index user_name_index on users ("
- + "User_name ASC )";
- Statement.exe cute (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();}
The users table has been created, which includes three columns: ID, user_name, and password. ID is the primary key. The generated by default as identity function is similar to sequence, and identity is the column automatically added,
Generated by always as identity
Generated by default as identity
By always and by default indicate how to generate this identity.
By always is automatically generated by the system.
By default is a value that can be specified by the user.
Compile the JavaBean corresponding to the users table (this is not to be said ),:
Java code
- 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;
- }
- }
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;}}
Next, you can add, delete, modify, and query the database:
Insert data:
Java code
- 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.exe cute ();
- User. setid (this. GETID (connection ));
- Connection. Commit ();
- } Catch (sqlexception e ){
- Rollback (connection );
- Throw new runtimeexception (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 code
- Private long GETID (connection) throws sqlexception {
- Callablestatement = connection
- . Preparecall ("values identity_val_local ()");
- Resultset = callablestatement.exe cutequery ();
- Resultset. Next ();
- Long id = resultset. getlong (1 );
- Resultset. Close ();
- Callablestatement. Close ();
- Return ID;
- }
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;}
The GETID method obtains the default system id value through identity_val_local (), while the identity_val_local () function can be executed after the insert statement is executed, returns the value generated by the System ID. I still think about curr_val of sequence.
Modify data:
Java code
- 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.exe cute ();
- Connection. Commit ();
- } Catch (sqlexception e ){
- Rollback (connection );
- Throw new runtimeexception (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);}}}
Delete data:
Java code
- 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.exe cute ();
- Connection. Commit ();
- } Catch (sqlexception e ){
- Rollback (connection );
- Throw new runtimeexception (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);}}}
Query data:
Java code
- 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 = statement.exe cutequery ();
- 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 );
- }
- }
- }