Program 1: Establishing a Connection with H2
This program establishes a connection between a Java application and an H2 database using JDBC.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class H2ConnectionExample {
public static void main(String[] args) {
String url =
"jdbc:h2:D:/test/jdbc_demo";
String username = "sa";
String password = "password";
try {
Connection con =
DriverManager.getConnection(
url, username, password);
System.out.println(
"Connected to H2 database successfully.");
con.close();
} catch (SQLException e) {
System.out.println(
"Connection failed: " +
e.getMessage());
}
}
}Execution and Output:
PS D:\test> javac -classpath ".;D:\test\h2-jdbc.jar" H2ConnectionExample.java
PS D:\test> java -classpath ".;D:\test\h2-jdbc.jar" H2ConnectionExample
Connected to H2 database successfully.Code language: CSS (css)
Program 2: Creating an Employee Table
This program creates an employee table in the H2 database using the Statement interface.
import java.sql.*;
public class CreateH2EmployeeTable {
public static void main(String[] args) {
String url =
"jdbc:h2:D:/test/jdbc_demo";
String sql =
"CREATE TABLE IF NOT EXISTS employee (" +
"employee_id INT PRIMARY KEY, " +
"employee_name VARCHAR(100), " +
"department VARCHAR(50), " +
"salary DECIMAL(10,2))";
try {
Connection con =
DriverManager.getConnection(
url, "sa", "password");
Statement stmt =
con.createStatement();
stmt.executeUpdate(sql);
System.out.println(
"Employee table created successfully.");
stmt.close();
con.close();
} catch (SQLException e) {
System.out.println(
"Error: " + e.getMessage());
}
}
}Execution and Output:
PS D:\test> javac -classpath ".;D:\test\h2-jdbc.jar" CreateH2EmployeeTable.java
PS D:\test> java -classpath ".;D:\test\h2-jdbc.jar" CreateH2EmployeeTable
Employee table created successfully.Code language: CSS (css)
Program 3: Inserting Records Using PreparedStatement
This program inserts an employee record into H2 using a parameterized SQL query.
import java.sql.*;
public class H2PreparedStatementExample {
public static void main(String[] args) {
String url =
"jdbc:h2:D:/test/jdbc_demo";
String sql =
"INSERT INTO employee " +
"(employee_id, employee_name, department, salary) " +
"VALUES (?, ?, ?, ?)";
try {
Connection con =
DriverManager.getConnection(
url, "sa", "password");
PreparedStatement ps =
con.prepareStatement(sql);
ps.setInt(1, 101);
ps.setString(2, "Ravi");
ps.setString(3, "IT");
ps.setDouble(4, 50000);
ps.executeUpdate();
System.out.println(
"Employee inserted successfully.");
ps.close();
con.close();
} catch (SQLException e) {
System.out.println(
"Error: " + e.getMessage());
}
}
}Execution and Output:
PS D:\test> javac -classpath ".;D:\test\h2-jdbc.jar" H2PreparedStatementExample.java
PS D:\test> java -classpath ".;D:\test\h2-jdbc.jar" H2PreparedStatementExample
Employee inserted successfully.Code language: CSS (css)
Program 4: Retrieving Records Using ResultSet
This program retrieves employee records from the H2 database using Statement and ResultSet.
import java.sql.*;
public class H2ResultSetExample {
public static void main(String[] args) {
String url =
"jdbc:h2:D:/test/jdbc_demo";
try {
Connection con =
DriverManager.getConnection(
url, "sa", "password");
Statement stmt =
con.createStatement();
ResultSet rs =
stmt.executeQuery(
"SELECT * FROM employee");
System.out.println(
"Employee Details");
System.out.println(
"-------------------------");
while (rs.next()) {
System.out.println(
rs.getInt("employee_id") + " " +
rs.getString("employee_name") + " " +
rs.getString("department") + " " +
rs.getDouble("salary"));
}
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}Execution and Output:
PS D:\test> javac -classpath ".;D:\test\h2-jdbc.jar" H2ResultSetExample.java
PS D:\test> java -classpath ".;D:\test\h2-jdbc.jar" H2ResultSetExample
Employee Details
-------------------------
101 Ravi IT 50000.0Code language: CSS (css)
Program 5: Updating Records Using PreparedStatement
This program updates an employee’s salary using a parameterized SQL statement.
import java.sql.*;
public class H2UpdateExample {
public static void main(String[] args) {
String url =
"jdbc:h2:D:/test/jdbc_demo";
String sql =
"UPDATE employee " +
"SET salary = ? " +
"WHERE employee_id = ?";
try {
Connection con =
DriverManager.getConnection(
url, "sa", "password");
PreparedStatement ps =
con.prepareStatement(sql);
ps.setDouble(1, 60000);
ps.setInt(2, 101);
int rows =
ps.executeUpdate();
System.out.println(
rows + " record updated.");
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}Execution and Output:
PS D:\test> javac -classpath ".;D:\test\h2-jdbc.jar" H2UpdateExample.java
PS D:\test> java -classpath ".;D:\test\h2-jdbc.jar" H2UpdateExample
1 record updated.Code language: CSS (css)
Program 6: Deleting Records Using PreparedStatement
This program deletes an employee record from H2 using PreparedStatement.
import java.sql.*;
public class H2DeleteExample {
public static void main(String[] args) {
String url =
"jdbc:h2:D:/test/jdbc_demo";
String sql =
"DELETE FROM employee " +
"WHERE employee_id = ?";
try {
Connection con =
DriverManager.getConnection(
url, "sa", "password");
PreparedStatement ps =
con.prepareStatement(sql);
ps.setInt(1, 101);
int rows =
ps.executeUpdate();
System.out.println(
rows + " record deleted.");
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}Execution and Output:
PS D:\test> javac -classpath ".;D:\test\h2-jdbc.jar" H2DeleteExample.java
PS D:\test> java -classpath ".;D:\test\h2-jdbc.jar" H2DeleteExample
1 record deleted.Code language: CSS (css)
Program 7: Performing Batch Insert Using PreparedStatement
This program inserts multiple employee records using JDBC batch processing.
import java.sql.*;
public class H2BatchExample {
public static void main(String[] args) {
String url =
"jdbc:h2:D:/test/jdbc_demo";
String sql =
"INSERT INTO employee " +
"(employee_id, employee_name, department, salary) " +
"VALUES (?, ?, ?, ?)";
try {
Connection con =
DriverManager.getConnection(
url, "sa", "password");
PreparedStatement ps =
con.prepareStatement(sql);
ps.setInt(1, 201);
ps.setString(2, "Arun");
ps.setString(3, "IT");
ps.setDouble(4, 45000);
ps.addBatch();
ps.setInt(1, 202);
ps.setString(2, "Priya");
ps.setString(3, "HR");
ps.setDouble(4, 42000);
ps.addBatch();
ps.setInt(1, 203);
ps.setString(2, "Kiran");
ps.setString(3, "Finance");
ps.setDouble(4, 48000);
ps.addBatch();
int[] result =
ps.executeBatch();
System.out.println(
result.length +
" records processed in batch.");
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}Execution and Output:
PS D:\test> javac -classpath ".;D:\test\h2-jdbc.jar" H2BatchExample.java
PS D:\test> java -classpath ".;D:\test\h2-jdbc.jar" H2BatchExample
3 records processed in batch.Code language: CSS (css)
Program 8: Using Transactions with commit() and rollback()
This program performs multiple updates within a transaction. If the operations are successful, commit() saves them. If an error occurs, rollback() reverses the changes.
import java.sql.*;
public class H2TransactionExample {
public static void main(String[] args) {
String url =
"jdbc:h2:D:/test/jdbc_demo";
Connection con = null;
try {
con =
DriverManager.getConnection(
url, "sa", "password");
con.setAutoCommit(false);
PreparedStatement ps =
con.prepareStatement(
"UPDATE employee " +
"SET salary = salary + ? " +
"WHERE employee_id = ?");
ps.setDouble(1, 5000);
ps.setInt(2, 201);
ps.executeUpdate();
ps.setDouble(1, 3000);
ps.setInt(2, 202);
ps.executeUpdate();
con.commit();
System.out.println(
"Transaction committed successfully.");
ps.close();
con.close();
} catch (SQLException e) {
System.out.println(
"Transaction failed.");
if (con != null) {
try {
con.rollback();
System.out.println(
"Transaction rolled back.");
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
}Execution and Output:
PS D:\test> javac -classpath ".;D:\test\h2-jdbc.jar" H2TransactionExample.java
PS D:\test> java -classpath ".;D:\test\h2-jdbc.jar" H2TransactionExample
Transaction committed successfully.Code language: CSS (css)
Program 9: Using Savepoint in H2
This program creates a savepoint after the first update and rolls back the second update to that savepoint.
import java.sql.*;
public class H2SavepointExample {
public static void main(String[] args) {
String url =
"jdbc:h2:D:/test/jdbc_demo";
try {
Connection con =
DriverManager.getConnection(
url, "sa", "password");
con.setAutoCommit(false);
Statement stmt =
con.createStatement();
// First update
stmt.executeUpdate(
"UPDATE employee " +
"SET salary = salary + 2000 " +
"WHERE employee_id = 201");
System.out.println(
"First update completed.");
// Create savepoint
Savepoint savepoint =
con.setSavepoint("AfterFirstUpdate");
System.out.println(
"Savepoint created.");
// Second update
stmt.executeUpdate(
"UPDATE employee " +
"SET salary = salary + 5000 " +
"WHERE employee_id = 202");
System.out.println(
"Second update completed.");
// Roll back to savepoint
con.rollback(savepoint);
System.out.println(
"Rolled back to savepoint.");
// Commit remaining changes
con.commit();
System.out.println(
"Transaction committed.");
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}Execution and Output:
PS D:\test> javac -classpath ".;D:\test\h2-jdbc.jar" H2SavepointExample.java
PS D:\test> java -classpath ".;D:\test\h2-jdbc.jar" H2SavepointExample
First update completed.
Savepoint created.
Second update completed.
Rolled back to savepoint.
Transaction committed.Code language: CSS (css)
Program 10: Calling an H2 Function Using CallableStatement
H2 supports Java-based database functions. This example creates a simple Java method and registers it as an H2 alias. The Java application then calls the function using CallableStatement.
import java.sql.*;
public class H2CallableStatementExample {
public static String getGreeting(String name) {
return "Hello, " + name;
}
public static void main(String[] args) {
String url =
"jdbc:h2:D:/test/jdbc_demo";
try {
Connection con =
DriverManager.getConnection(
url, "sa", "password");
Statement stmt =
con.createStatement();
stmt.execute(
"CREATE ALIAS IF NOT EXISTS " +
"GET_GREETING FOR " +
"'H2CallableStatementExample.getGreeting'");
CallableStatement cs =
con.prepareCall(
"{? = CALL GET_GREETING(?)}");
cs.registerOutParameter(
1, Types.VARCHAR);
cs.setString(2, "Ravi");
cs.execute();
String result =
cs.getString(1);
System.out.println(
"Result: " + result);
cs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}Execution and Output:
PS D:\test> javac -classpath ".;D:\test\h2-jdbc.jar" H2CallableStatementExample.java
PS D:\test> java -classpath ".;D:\test\h2-jdbc.jar" H2CallableStatementExample
Result: Hello, RaviCode language: CSS (css)
Note: H2’s routine/function mechanism is different from MySQL or SQL Server stored procedures. For a JDBC syllabus, this example demonstrates CallableStatement with an H2 function rather than pretending H2 has the same stored-procedure syntax as SQL Server.
