🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Table of Contents
- Introduction
- Setting Up the H2 Database
- JDBC Driver and Dependencies
- Connecting to H2 Database
- CRUD Operations
- Create
- Read
- Update
- Delete
- Conclusion
1. Introduction
H2 is a powerful, fast, and lightweight database that is easy to embed in Java applications. It supports standard SQL and JDBC, making it an excellent choice for development, testing, and lightweight applications.
2. Setting Up the H2 Database
Download the H2 database from the official website and follow the installation instructions.
You can start the H2 database in server mode by running the following command:
java -jar h2*.jar
This will start the H2 database and open the web console at http://localhost:8082.
3. JDBC Driver and Dependencies
To connect to H2 from Java, you need the H2 JDBC driver. Add the following dependency to your pom.xml if you are using Maven:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.1.214</version>
</dependency>
4. Connecting to the H2 Database
Let's write a simple Java program to connect to the H2 database.
Example: Connect to H2 Database
package com.example.h2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class H2DatabaseConnection {
private static final String JDBC_URL = "jdbc:h2:~/test;AUTO_SERVER=TRUE";
private static final String USER = "sa";
private static final String PASSWORD = "";
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD)) {
System.out.println("Connected to H2 database successfully!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
5. CRUD Operations
5.1 Create Table
Let's create a table named products.
package com.example.h2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateTableExample {
private static final String JDBC_URL = "jdbc:h2:~/test;AUTO_SERVER=TRUE";
private static final String USER = "sa";
private static final String PASSWORD = "";
public static void main(String[] args) {
String createTableSQL = "CREATE TABLE IF NOT EXISTS products (" +
"id INT AUTO_INCREMENT PRIMARY KEY, " +
"name VARCHAR(255), " +
"price DECIMAL(10, 2))";
try (Connection connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
Statement statement = connection.createStatement()) {
statement.execute(createTableSQL);
System.out.println("Table 'products' created successfully!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
5.2 Insert Record
package com.example.h2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class InsertRecordExample {
private static final String JDBC_URL = "jdbc:h2:~/test;AUTO_SERVER=TRUE";
private static final String USER = "sa";
private static final String PASSWORD = "";
public static void main(String[] args) {
String insertSQL = "INSERT INTO products (name, price) VALUES (?, ?)";
try (Connection connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
PreparedStatement preparedStatement = connection.prepareStatement(insertSQL)) {
preparedStatement.setString(1, "Laptop");
preparedStatement.setBigDecimal(2, new java.math.BigDecimal("799.99"));
preparedStatement.executeUpdate();
System.out.println("Record inserted successfully!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
5.3 Read Records
package com.example.h2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ReadRecordsExample {
private static final String JDBC_URL = "jdbc:h2:~/test;AUTO_SERVER=TRUE";
private static final String USER = "sa";
private static final String PASSWORD = "";
public static void main(String[] args) {
String selectSQL = "SELECT * FROM products";
try (Connection connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(selectSQL)) {
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
java.math.BigDecimal price = resultSet.getBigDecimal("price");
System.out.println("ID: " + id + ", Name: " + name + ", Price: " + price);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
5.4 Update Record
package com.example.h2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class UpdateRecordExample {
private static final String JDBC_URL = "jdbc:h2:~/test;AUTO_SERVER=TRUE";
private static final String USER = "sa";
private static final String PASSWORD = "";
public static void main(String[] args) {
String updateSQL = "UPDATE products SET price = ? WHERE name = ?";
try (Connection connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
PreparedStatement preparedStatement = connection.prepareStatement(updateSQL)) {
preparedStatement.setBigDecimal(1, new java.math.BigDecimal("899.99"));
preparedStatement.setString(2, "Laptop");
preparedStatement.executeUpdate();
System.out.println("Record updated successfully!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
5.5 Delete Record
package com.example.h2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DeleteRecordExample {
private static final String JDBC_URL = "jdbc:h2:~/test;AUTO_SERVER=TRUE";
private static final String USER = "sa";
private static final String PASSWORD = "";
public static void main(String[] args) {
String deleteSQL = "DELETE FROM products WHERE name = ?";
try (Connection connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
PreparedStatement preparedStatement = connection.prepareStatement(deleteSQL)) {
preparedStatement.setString(1, "Laptop");
preparedStatement.executeUpdate();
System.out.println("Record deleted successfully!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
6. Conclusion
In this tutorial, we learned how to connect to the H2 database using Java JDBC. We also covered basic CRUD operations: create, read, update, and delete. H2 is a lightweight and fast database that is easy to use with Java applications. Using the techniques shown in this tutorial, you can efficiently manage your data with the H2 database.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
insert part is not working
ReplyDelete