h2 Database Tutorial
h2 Database Tutorial
0
H2 Database
In this brief tutorial, we will look closely at the various features of H2 and its commands,
one of the best open-source, multi-model, next generation SQL product.
Audience
This tutorial is designed for all those software professionals who would like to learn how
to use H2 database in simple and easy steps. This tutorial will give you a good overall
understanding on the basic concepts of H2 database.
Prerequisites
H2 database primarily deals with relational data. Hence, you should first of all have a good
understanding of the concepts of databases in general, especially RDBMS concepts, before
going ahead with this tutorial.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com.
1
H2 Database
Table of Contents
About the Tutorial ........................................................................................................................................... 1
Audience .......................................................................................................................................................... 1
Prerequisites .................................................................................................................................................... 1
Disclaimer & Copyright .................................................................................................................................... 1
Table of Contents ............................................................................................................................................ 2
H2 BASICS ................................................................................................................................ 4
1. H2 Introduction ...................................................................................................................................... 5
2. H2 Installation ........................................................................................................................................ 7
Verify Java Installation ..................................................................................................................................... 7
Install H2 Database .......................................................................................................................................... 7
3. H2 Select .............................................................................................................................................. 12
4. H2 Insert .............................................................................................................................................. 15
5. H2 Update ............................................................................................................................................ 17
6. H2 Delete ............................................................................................................................................. 20
7. H2 Backup ............................................................................................................................................ 22
8. H2 Call .................................................................................................................................................. 23
9. H2 Explain ............................................................................................................................................ 24
2
H2 Database
15. H2 Truncate.......................................................................................................................................... 38
17. H2 Grant............................................................................................................................................... 40
Grant Right .................................................................................................................................................... 40
Grant Alter Any Schema ................................................................................................................................ 40
3
H2 Database
H2 Basics
4
1. H2 Introduction H2 Database
This database can be used in embedded mode or in server mode. Following are the main
features of H2 database:
Features of H2 Database
The main features of H2 Database are as follows:
Additional Features
Following are some additional features of H2 Database:
H2 contains scrollable and updatable result set support, large result set, external
result sorting, functions can return a result set.
5
H2 Database
Components in H2 Database
In order to use H2 Database, you need to have the following components:
A web browser
A H2 console server
This is a client/server application, so both server and client (a browser) are required to
run it.
6
2. H2 Installation H2 Database
H2 is a database written in Java. We can easily embed this database to our application by
using JDBC. We can run this on many different platforms or any version of Java Runtime
Environment. However, before installing the database, there should be Java installed in
the system.
java version
If JDk is successfully installed in the system, then we will get the following output.
If JDK is not installed in the system, then visit the following link to Install JDK.
Install H2 Database
We can run this database on many different platforms. In this chapter, we will learn about
H2 Database installation on Windows.
Click the Windows installer for downloading the Windows supportable H2 database after
downloading the .exe file. In this case, we are using H2 Database with the version 1.4.192.
The following screen is the first step in the installation process. Provide a path where we
want to install the H2 database server as shown in the following screenshot.
7
H2 Database
8
H2 Database
In the above screenshot, click the Install button to start the installation process. After
installation, we get the following screenshot.
9
H2 Database
Fill all the details in the above dialog box such as Saved Settings, Settings Name, Driver
Class, JDBC URL, User Name, and Password. In the JDBC URL, specify the database is
located and the database name. User Name and Password are the fields for user name
and password of the database. Click Connect.
10
H2 Database
H2 Data Manipulation
11
3. H2 Select H2 Database
Select command is used to fetch record data from a table or multiple tables. If we design
a select query, then it returns data in the form of result table called result sets.
Syntax
The basic syntax of SELECT statement is as follows:
Example
Consider the CUSTOMER table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
12
H2 Database
To get the customer table along with the given data, execute the following queries.
CREATE TABLE CUSTOMER (id number, name varchar(20), age number, address
varchar(20), salary number);
The following command is an example, which would fetch ID, Name and Salary fields of
the customers available in the CUSTOMER table.
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 1 | Ramesh | 2000.00 |
| 2 | Khilan | 1500.00 |
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
Use the following query to fetch all the fields of CUSTOMERS table.
13
H2 Database
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
14
4. H2 Insert H2 Database
The SQL INSERT statement is used to add new rows of data to a table in the database.
Syntax
Following is the basic syntax of INSERT INTO statement.
Using this INSERT statement, we can insert a new record or new rows into a table. When
using DIRECT clause, the results are directly affected to the target table without any
intermediate step. However, while adding values for all the columns of the table, make
sure the order of the values is in the same order as the columns in the table.
Example
Let us take an example and try to insert the following given records into the Customer
table.
6 Komal 22 MP 4500
15
H2 Database
We can get all the given records into the customer table by executing the following
commands.
16
5. H2 Update H2 Database
The UPDATE query is used to update or modify the existing records in a table. We can use
WHERE clause with UPDATE query to update the selected rows, otherwise all the rows
would be affected.
Syntax
Following is the basic syntax of the UPDATE query.
In this UPDATE syntax, we can combine more than one condition by using AND or OR
clauses.
Example
Consider the CUSTOMER table having the following records.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
17
H2 Database
If you want to get the customer table along with the given data, execute the following
queries.
CREATE TABLE CUSTOMER (id number, name varchar(20), age number, address
varchar(20), salary number);
The following command is an example, which would update ADDRESS for a customer
whose ID is 6:
Now, CUSTOMERS table would have the following records. We can check the customer
table records by executing the following query.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | Pune | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
To modify all ADDRESS and SALARY column values in CUSTOMERS table, we need not use
the WHERE clause. The UPDATE query would be as follows:
18
H2 Database
Now, CUSTOMERS table would have the following records. We can check the customer
table records by executing the following query.
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 1 | Ramesh | 32 | Pune | 1000.00 |
| 2 | Khilan | 25 | Pune | 1000.00 |
| 3 | kaushik | 23 | Pune | 1000.00 |
| 4 | Chaitali | 25 | Pune | 1000.00 |
| 5 | Hardik | 27 | Pune | 1000.00 |
| 6 | Komal | 22 | Pune | 1000.00 |
| 7 | Muffy | 24 | Pune | 1000.00 |
+----+----------+-----+---------+---------+
19
6. H2 Delete H2 Database
The SQL DELETE query is used to delete the existing records from a table. We can use
WHERE clause with DELETE query to delete selected records, otherwise all the records will
be deleted.
Syntax
Following is the generic query syntax of the delete command.
The above syntax deletes the rows from a table. If TOP or LIMIT is specified, at most the
specified number of rows are deleted (no limit if null or smaller than zero).
Example
Consider the CUSTOMER table having the following records.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The following command will delete the details of the customer, whose ID is 6.
After execution of the above command, check the Customer table by executing the
following command.
20
H2 Database
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
If we want to DELETE all the records from CUSTOMERS table, we do not use WHERE clause.
The DELETE query would be as follows.
After executing the above command, no records will be available in the Customer table.
21
7. H2 Backup H2 Database
BACKUP is the command used to take database backup into a separate .zip file. Objects
are not locked, and when it takes backup the transaction log is also copied. Admin rights
are required to execute this command.
Syntax
Following is the generic syntax of the Backup command.
BACKUP TO fileNameString;
Example
In this example, let us take a backup of the current database into backup.zip file. Use
the following command for the same.
BACKUP TO 'backup.zip';
On executing the above command, you will get the backup.zip file in your local file system.
22
8. H2 Call H2 Database
CALL is a SQL command which belongs to H2 database server. This command is used to
calculate a simple expression. It returns the result of the given expression in a single
column field. When it returns an array of results, then each element in the array is
displayed as a column value.
Syntax
Following is the generic syntax of the CALL command.
CALL expression;
Example
Let us take an example and execute an arithmetic expression (15*25) using call command.
CALL 15*25;
375
375
23
9. H2 Explain H2 Database
EXPLAIN command displays the execution plan for a statement. When we execute a
statement using EXPLAIN ANALYZE command, the query plan will include the actual row
scan count for each table.
Syntax
Following is the generic syntax of the EXPLAIN command.
Along with this syntax we can use select, insert, delete, and merge.
Example
This example explains the query plan details of the customer with ID 1.
PLAN
SELECT
CUSTOMER.ID,
CUSTOMER.NAME,
CUSTOMER.AGE,
CUSTOMER.ADDRESS,
CUSTOMER.SALARY
FROM PUBLIC.CUSTOMER
/* PUBLIC.CUSTOMER.tableScan */
WHERE ID = 1
24
10. H2 Merge H2 Database
MERGE command is used to update the existing rows and insert new rows into a table.
The primary key column plays an important role while using this command; it is used to
find the row.
Syntax
Following is the generic syntax of the MERGE command.
In the above syntax, the KEY clause is used to specify the primary key column name.
Along with VALUES clause, we can use primitive values to insert or we can retrieve and
store another table values into this table using the select command.
Example
In this example, let us try to add a new record into Customers table. Following are the
details of the new record in the table.
ID 8
NAME Lokesh
AGE 32
ADDRESS Hyderabad
SALARY 2500
Using the following query, let us insert the given record into the H2 database query.
MERGE INTO CUSTOMER KEY (ID) VALUES (8, 'Lokesh', 32, 'Hyderabad', 2500);
Update count: 1
Let us verify the records of the Customer table by executing the following query.
25
H2 Database
6 Komal 22 MP 4500
Now let us try to update the record using the Merge command. Following are the details
of the record to be updated.
ID 8
NAME Loki
AGE 32
ADDRESS Hyderabad
SALARY 3000
Use the following query to insert the given record into the H2 database query.
MERGE INTO CUSTOMER KEY (ID) VALUES (8, 'Loki', 32, 'Hyderabad', 3000);
Update count: 1
Let us verify the records of the Customer table by executing the following query.
26
H2 Database
6 Komal 22 MP 4500
27
11. H2 Show H2 Database
SHOW is a command used to display the list of Schemas, Tables, or Columns of the table.
Syntax
Following is the generic syntax of the SHOW command.
Example
The following command can be used to get the list of tables in the current database.
SHOW TABLES;
TABLE_NAME TABLE_SCHEMA
CUSTOMER PUBLIC
EMP PUBLIC
28
H2 Database
H2 Data Definition
29
12. H2 Create H2 Database
CREATE is a generic SQL command used to create Tables, Schemas, Sequences, Views,
and Users in H2 Database server.
Create Table
Create Table is a command used to create a user-defined table in the current database.
Syntax
Following is the generic syntax for the Create Table command.
By using the generic syntax of the Create Table command, we can create different types
of tables such as cached tables, memory tables, and temporary tables. Following is the list
to describe different clauses from the given syntax.
CACHED: The cached tables are the default type for regular tables. This means the
number of rows is not limited by the main memory.
MEMORY: The memory tables are the default type for temporary tables. This
means the memory tables should not get too large and the index data is kept in
the main memory.
ENGINE: The ENGINE option is only required when custom table implementations
are used.
Example
In this example, let us create a table named tutorials_tbl using the following given data.
1 ID Int
2 Title Varchar(50)
3 Author Varchar(20)
4 Submission_date Date
The following query is used to create a table tutorials_tbl along with the given column
data.
Create Schema
Create Schema is a command used to create a user-dependent schema under a particular
authorization (under the currently registered user).
Syntax
Following is the generic syntax of the Create Schema command.
In the above generic syntax, AUTHORIZATION is a keyword used to provide the respective
user name. This command is optional which means if we are not providing the user name,
then it will consider the current user. The user that executes the command must have
admin rights, as well as the owner.
31
H2 Database
Example
In this example, let us create a schema named test_schema under SA user, using the
following command.
Create Sequence
Sequence is concept which is used to generate a number by following a sequence for id or
any random column values.
Syntax
Following is the generic syntax of the create sequence command.
This generic syntax is used to create a sequence. The datatype of a sequence is BIGINT.
In this the sequence, values are never re-used, even when the transaction is roll backed.
Example
In this example, let us create a sequence named SEQ_ID, using the following query.
32
13. H2 Alter H2 Database
ALTER is a command used to change the table structure by adding different clauses to the
alter command. Based on the scenario, we need to add respective clause to the alter
command. In this chapter, we will discuss various scenarios of alter command.
Syntax
Following is the generic syntax of the Alter Table Add command.
Example
In this example, we will add a new column start_date to the table tutorials_tbl. The
datatype for start_date is Date. Following is the query to add a new column.
The required indexes are automatically created if they dont exist yet. It is not possible to
disable checking for unique constraint. This command commits an open transaction in this
connection.
Syntax
Following is the generic syntax of the Alter table add constraint command.
33
H2 Database
Example
In this example, let us add a primary key constraint (tutorials_tbl_pk) to the column id
of the table tutorials_tbl, using the following query.
Syntax
Following is the generic syntax of the Alter Table Rename Constraint command.
While using this syntax, make sure that the old constraint name should exist with the
respective column.
Example
In this example, we will change the primary key constraint name of the table tutorials_tbl
from tutorials_tbl_pk to tutorials_tbl_pk_constraint. Following is the query to do so.
Syntax
Following is the generic syntax of the Alter Table Alter Column command.
34
H2 Database
| { RENAME TO name }
| { RESTART WITH long }
| { SELECTIVITY int }
| { SET DEFAULT expression }
| { SET NULL }
| { SET NOT NULL } }
SELECTIVITY command sets the selectivity (1-100) for a column. Based on the
selectivity value we can image the value of the column.
Example
In this example, we will rename the column of the table tutorials_tbl from Title to
Tutorial_Title using the following query.
In a similar way, we can perform different scenarios with the ALTER command.
35
14. H2 Drop H2 Database
DROP is a command taken from the generic SQL grammar. This command is used to delete
a database component and its structure from the memory. There are different scenarios
with the Drop command that we will discuss in this chapter.
Drop Table
Drop Table is a command that deletes the respective table and its structure.
Syntax
Following is the generic syntax of the Drop Table command.
The command will fail if we are using RESTRICT and the table having dependent views
exist. All dependent views are dropped, when we are using CASCADE keyword.
Example
In this example, we will drop a table named test using the following query.
Drop Schema
Drop Schema is a command that drops a respective schema from the database server. It
will not work from the current schema.
Syntax
DROP SCHEMA [ IF EXISTS ] schemaName
Example
In this example, we will drop a schema named test_schema using the following query.
36
H2 Database
Drop Sequence
Drop Sequence is a command used to drop a sequence from the table structure.
Syntax
Following is the generic syntax of the Drop Sequence command.
Example
In this example, we will drop a sequence named sequence_id. Following is the command.
Drop View
Drop View is a command used to drop the existing view. All dependent views are dropped
as well if the CASCADE clause is used.
Syntax
Following is the generic syntax of the Drop View command.
Example
In this example, we will drop a view named sample_view using the following query.
37
15. H2 Truncate H2 Database
TRUNCATE is a command used to delete the data from the table. Unlike DELETE FROM
without WHERE clause, this command cannot be rolled back. This command commits an
open transaction in this connection.
Syntax
Following is the generic syntax of the truncate command.
Example
In this example, we will truncate a table named test using the following query.
38
16. H2 Commit H2 Database
COMMIT is a command from the SQL grammar used to commit the transaction. We can
either commit the specific transaction or we can commit the currently executed
transaction.
Syntax
There are two different syntaxes for COMMIT command.
Following is the generic syntax for the commit command to commit the current
transaction.
COMMIT [ WORK ]
Following is the generic syntax for the commit command to commit the specific
transaction.
Example 1
In this example, let us commit the current transaction using the following command.
COMMIT
Committed successfully
Example 2
In this example, we will commit the transaction named tx_test using the following
command.
Committed successfully
39
17. H2 Grant H2 Database
Grant is a command coming from the SQL grammar used to grant the rights to a table, to
a user, or to a role. Admin rights are required to execute this command. This command
commits an open transaction in this connection.
Grant Right
Grant Right is a command to provide admin rights to a table, to a user, or to a role.
Syntax
Following is the generic syntax of the Grant command.
Example
In this example, we will grant the test table as read-only using the following command.
Grant successfully
Syntax
Following is the generic syntax of the Grant Alter Any Schema command.
Example
In this example, we will grant altering privileges of a schema to a user named test_user.
Make sure that test_user exists. Following is the query to grant altering privileges.
40
H2 Database
41
18. H2 Savepoint H2 Database
Syntax
Following is the generic syntax of the Savepoint command.
SAVEPOINT savepointName
Example
In this example, we will create a Savepoint named Half_Done using the following
command.
SAVEPOINT Half_Done;
Savepoint created
42
19. H2 Rollback H2 Database
ROLLBACK is a command from the SQL grammar used to roll back the transaction to a
Savepoint or to the previous transaction. By using this command, we can either roll back
to the specific Savepoint or we can roll back to the previous executed transaction.
Syntax
There are two different syntaxes for ROLLABCK command.
Following is the generic syntax of the Rollback command to the specific transaction.
Example 1
In this example, we will roll back the current transaction to a Savepoint named sp1_test
using the following command.
ROLLBACK sp1_test;
Rollback successfully
Example 2
In the following example, we will roll back the complete transaction named tx_test using
the given command.
Rollback successfully
43
20. H2 JDBC Connection H2 Database
H2 is a JAVA database. We can interact with this database by using JDBC. In this chapter,
we will see how to create a JDBC connection with H2 database and the CRUD operations
with the H2 database.
Class.forName ("org.h2.Driver");
Statement st = conn.createStatement();
Stmt.executeUpdate("sql statement");
conn.close();
Create Table
In this example, we will write a program for create table. Consider a table named
Registration having the following fields.
Sr. No. Column Name Data Type NOT NULL Primary Key
2 First Varchar(255) No No
3 Last Varchar(255) No No
4 Age Number No No
44
H2 Database
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
// Database credentials
static final String USER = "sa";
static final String PASS = "";
stmt.executeUpdate(sql);
45
H2 Database
Save the above program into H2jdbcCreateDemo.java. Compile and execute the above
program by executing the following commands in the command prompt.
\>javac H2jdbcCreateDemo.java
\>java H2jdbcCreateDemo
46
H2 Database
Connecting to database...
Creating table in given database...
Created table in given database...
Goodbye!
After this execution, we can check the table created using the H2 SQL interface.
Insert Records
In this example, we will write a program for inserting records. Let us insert the following
records into the table Registration.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
// Database credentials
static final String USER = "sa";
static final String PASS = "";
47
H2 Database
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " +
"VALUES (102, 'Zaid', 'Khan', 30)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " +
"VALUES(103, 'Sumit', 'Mittal', 28)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
48
H2 Database
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
}
Save the above program into H2jdbcInsertDemo.java. Compile and execute the above
program by executing the following commands in the command prompt.
\>javac H2jdbcInsertDemo.java
\>java H2jdbcInsertDemo
Read Record
In this example, we will write a program for reading records. Let us try to read all records
from the table Registration.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
// Database credentials
static final String USER = "sa";
static final String PASS = "";
50
H2 Database
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
}
51
H2 Database
Save the above program into H2jdbcReadDemo.java. Compile and execute the above
program by executing the following commands in the command prompt.
\>javac H2jdbcReadDemo.java
\>java H2jdbcReadDemo
Update Records
In this example, we will write a program to update records. Let us try to read all records
from the table Registration.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
// Database credentials
static final String USER = "sa";
static final String PASS = "";
52
H2 Database
try{
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
}catch(SQLException se){
//Handle errors for JDBC
53
H2 Database
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
}
Save the above program into H2jdbcUpdateDemo.java. Compile and execute the above
program by executing the following commands in the command prompt.
\>javac H2jdbcUpdateDemo.java
\>java H2jdbcUpdateDemo
54
H2 Database
Delete Records
In this example, we will write a program to delete records. Let us try to read all records
from the table Registration.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
// Database credentials
static final String USER = "sa";
static final String PASS = "";
55
H2 Database
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
56
H2 Database
stmt.close();
}catch(SQLException se2){
Save the above program into H2jdbcDeleteDemo.java. Compile and execute the above
program by executing the following commands in the command prompt.
\>javac H2jdbcDeleteDemo.java
\>java H2jdbcDeleteDemo
57