Friday, 6 March 2015

Connecting to H2 database using JDBC

Step 1: Open Eclipse and create Maven project




Set Group Id and Artifact Id as "H2_learn" and press Finish.

Project structure looks like below.


Step 2: Open pom.xml and add maven dependencies for H2 database.

Pom.xml looks like below.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>H2_learn</groupId>
 <artifactId>H2_learn</artifactId>
 <version>0.0.1-SNAPSHOT</version>

 <dependencies>
  <dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <version>1.4.185</version>
  </dependency>
 </dependencies>
</project>

Step 3: Use following java program to create and insert data into employee table.

import java.sql.*;

public class TestH2 {
 private static Connection conn = null;

 /* Get connection object */
 static Connection getConnection() {
  try {
   Class.forName("org.h2.Driver");
   conn = DriverManager.getConnection("jdbc:h2:~/test", "sa", "");
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return conn;
 }

 public static void main(String args[]) throws SQLException {
  
  getConnection();
  
  /* Create table employee */
  String dropTable = "DROP TABLE employee;";
  String createTable = "CREATE TABLE employee (id int, name varchar(30), PRIMARY KEY(id))";
  Statement stmt = conn.createStatement();
  stmt.execute(dropTable);
  stmt.execute(createTable);

  /* Insert data to employee table */
  String insertQuery = "INSERT INTO employee values(1, \'Krishna\')";
  stmt.execute(insertQuery);
  insertQuery = "INSERT INTO employee values(2, \'Arjun\')";
  stmt.execute(insertQuery);

  String selectQuery = "SELECT * FROM employee";
  ResultSet rs = stmt.executeQuery(selectQuery);

  while (rs.next()) {
   int id = rs.getInt("id");
   String name = rs.getString("name");
   System.out.println(id + " " + name);
  }
  rs.close();
  conn.close();
 }
}

Output

1 Krishna
2 Arjun

Final project structure looks like below.



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment