H2 Database - Quick Guide H2 Database - Introduction
H2 Database - Quick Guide H2 Database - Introduction
https://www.tutorialspoint.com/h2_database/h2_database_quick_guide.htm
Copyright © tutorialspoint.com
H2 DATABASE - INTRODUCTION
H2 is an open-source lightweight Java database. It can be embedded in Java
applications or run in the client-server mode. Mainly, H2 database can be
configured to run as inmemory database, which means that data will not persist on
the disk. Because of embedded database it is not used for production development,
but mostly used for development and testing.
This database can be used in embedded mode or in server mode. Following are the
main features of H2 database −
Features of H2 Database
Additional Features
Components in H2 Database
A web browser
A H2 console server
H2 DATABASE - INSTALLATION
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.
If JDK is installed in the system, try the following command to verify the Java
version.
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.
Download the latest version of H2 Database from the given link. In this link, you
will get the latest version of H2 database in two types. One is Windows Installer
type thatis.exefilethatis.exefile and second is Platform-Independent zip file for other
operating systems.
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.
In the above screenshot, click the Install button to start the installation process.
After installation, we get the following screenshot.
After installation, let us verify the database installation in the system. Click
Windows → type H2 Console → Click H2 console icon. Connect to the
URL http://localhost:8082. At the time of connecting, the H2 database will ask
for database registration as shown in the following screenshot.
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.
H2 DATABASE - SELECT
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
Example
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
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.
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
H2 DATABASE - INSERT
The SQL INSERT statement is used to add new rows of data to a table in the
database.
Syntax
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
We can get all the given records into the customer table by executing the following
commands.
H2 DATABASE - UPDATE
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
In this UPDATE syntax, we can combine more than one condition by using AND
or OR clauses.
Example
+----+----------+-----+-----------+----------+
| 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 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);
INSERT into CUSTOMER values (1, 'Ramesh', 32, 'Ahmedabad', 2000);
INSERT into CUSTOMER values (2, 'Khilan', 25, 'Delhi', 1500);
INSERT into CUSTOMER values (3, 'kaushik', 23, 'Kota', 2000);
INSERT into CUSTOMER values (4, 'Chaitali', 25, 'Mumbai', 6500);
INSERT into CUSTOMER values (5, 'Hardik', 27, 'Bhopal', 8500);
INSERT into CUSTOMER values (6, 'Komal', 22, 'MP', 4500);
INSERT into CUSTOMER values (7, 'Muffy', 24, 'Indore', 10000);
Now, CUSTOMERS table would have the following records. We can check the
customer table records by executing the following query.
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 |
+----+----------+-----+---------+---------+
H2 DATABASE - DELETE
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
Example
+----+----------+-----+-----------+----------+
| 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.
+----+----------+-----+-----------+----------+
| 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 |
| 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.
H2 DATABASE - BACKUP
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
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.
H2 DATABASE - CALL
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
CALL expression;
Example
Let us take an example and execute an arithmetic expression 15∗2515∗25 using call
command.
CALL 15*25;
The above command produces the following output.
375
375
H2 DATABASE - EXPLAIN
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
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.
H2 DATABASE - MERGE
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.
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.
6 Komal 22 MP 4500
H2 DATABASE - SHOW
SHOW is a command used to display the list of Schemas, Tables, or Columns of
the table.
Syntax
Example
The following command can be used to get the list of tables in the current
database.
SHOW TABLES;
CUSTOMER PUBLIC
EMP PUBLIC
H2 DATABASE - CREATE
CREATE is a generic SQL command used to create Tables, Schemas, Sequences,
Views, and Users in H2 Database server.
Create Table
Syntax
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.
TEMPORARY − Temporary tables are deleted while closing or opening a
database. Basically, temporary tables are of two types −
o GLOBAL type − Accessible by all connections.
o LOCAL type − Accessible by the current connection.
The default type for temporary tables is global type. Indexes of temporary
tables are kept in the main memory, unless the temporary table is created
using CREATE CACHED TABLE.
Example
In this example, let us create a table named tutorials_tbl using the following given
data.
1 ID Int
Varchar5050
2 Title
3 Author Varchar2020
4 Submission_date Date
The following query is used to create a table tutorials_tbl along with the given
column data.
Create Schema
Syntax
Example
In this example, let us create a schema named test_schema under SA user, using
the following command.
Create Sequence
Syntax
Example
In this example, let us create a sequence named SEQ_ID, using the following
query.
H2 DATABASE - ALTER
ALTER is a command used to change the table structure by adding different
clauses to the altercommand. 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.
Alter Table Add is a command used to add a new column to a table along with the
respective data type. This command commits the transaction in this connection.
Syntax
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.
ALTER TABLE tutorials_tbl ADD start_date DATE;
Alter table add constraint is a command used to add different constraints to the
table such as primary key, foreign key, not null, etc.
The required indexes are automatically created if they don’t 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.
Example
This command is used to rename the constraint name of a particular relation table.
This command commits an open transaction in this connection.
Syntax
Following is the generic syntax of the Alter Table Rename Constraint command.
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.
This command is used to change the structure and properties of the column of a
particular table. Changing the properties means changing the datatype of a column,
rename a column, change the identity value, or change the selectivity.
Syntax
Following is the generic syntax of the Alter Table Alter Column command.
In a similar way, we can perform different scenarios with the ALTER command.
H2 DATABASE - DROP
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
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
Example
In this example, we will drop a schema named test_schema using the following
query.
Drop Sequence
Drop Sequence is a command used to drop a sequence from the table structure.
Syntax
Example
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
Example
In this example, we will drop a view named sample_view using the following
query.
H2 DATABASE - TRUNCATE
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
Example
In this example, we will truncate a table named test using the following query.
H2 DATABASE - COMMIT
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
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
H2 DATABASE - GRANT
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
Syntax
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
H2 DATABASE - SAVEPOINT
SAVEPOINT is a command used to temporarily save the transaction. It is better to
maintain savepoints in your transaction as it is helpful to roll back the transaction
to the respective Savepoint whenever necessary.
Syntax
SAVEPOINT savepointName
Example
In this example, we will create a Savepoint named Half_Done using the following
command.
SAVEPOINT Half_Done;
Savepoint created
H2 DATABASE - ROLLBACK
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
Example 1
ROLLBACK sp1_test;
Rollback successfully
Example 2
Rollback successfully
Class.forName ("org.h2.Driver");
Stmt.executeUpdate("sql statement");
conn.close();
Create Table
In this example, we will write a program for create table. Consider a table
named Registrationhaving the following fields.
Varchar255255 No No
2 First
3 Last Varchar255255 No No
4 Age Number No No
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class H2jdbcCreateDemo {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "org.h2.Driver";
static final String DB_URL = "jdbc:h2:~/test";
// Database credentials
static final String USER = "sa";
static final String PASS = "";
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
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.
ID First Last Age
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);
sql = "INSERT INTO Registration " + "VALUES (101, 'Mahnaz',
'Fatma', 25)";
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...");
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 = "";
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 = "";
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) 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
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 = "";
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) 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 H2jdbcDeleteDemo.java. Compile and execute the
above program by executing the following commands in the command prompt.
\>javac H2jdbcDeleteDemo.java
\>java H2jdbcDeleteDemo