Thursday, August 4, 2016

HSQLDB With Java Example

INTRODUCTION

  • HSQLDB is called Hyper SQL Database and it is completely written in java.
  • Supports for embedding with java application as well as server mode.
  • Tables can be created in an in-memory or local disk.
  • It is 100% free and used in many of open source projects.

SOFTWARES & TOOLS

  1. HSQLDB
  2. Eclipse IDE (Mars 2)
  3. HSQLDB in-built DB Editor (Swing Based Application)

INSTALLATION

  1. Download latest HQLDB from https://sourceforge.net/projects/hsqldb/
  2. Unzip and copy to your local drive: C:\ranjiths\CommonSofties\hsqldb-2.3.4

CREATE DATABASE & TABLES

Go to C:\ranjiths\CommonSofties\hsqldb-2.3.4\bin and Click runManagerSwing.bat
Swing based Application will be opened and enter below details.

  1. Setting Name: JBR
  2. Type : HSQL Database Engine In-Memory
  3. Driver: org.hsqldb.jdbcDriver
  4. URL: jdbc:hsqldb:file:C:\ranjiths\jbr\hsqldb\db
  5. User: ranjith
  6. Password: sekar

Click OK

Create a table and insert some data.
CREATE TABLE users (
 user_id INTEGER NOT NULL CONSTRAINT EMP_NO_PK PRIMARY KEY,
 first_name VARCHAR(30) NOT NULL,
 last_name VARCHAR(30) NOT NULL,
 email VARCHAR(40),
 phone INTEGER
 );

INSERT INTO users VALUES(1,'Ranjith','Sekar','ranjith@gmail.com',96000);
INSERT INTO users VALUES(2,'Manoj','Kumar','manoj@gmail.com',88000);
INSERT INTO users VALUES(3,'Sachin','Tendulkar','sachin@gmail.com',77000);

EXAMPLE JAVA PROGRAM

  1. Create a Java Project in Eclipse
  2. Add all jars from C:\ranjiths\CommonSofties\hsqldb-2.3.4\lib into the project’s classpath.

package jbr.hsqldb;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class HSQLDBExample {
 public static void main(String[] args) {
   Connection connection = null;
   ResultSet resultSet = null;
   Statement statement = null;
   try {
     Class.forName("org.hsqldb.jdbcDriver");
     connection = DriverManager.getConnection("jdbc:hsqldb:file:
                  c:/ranjiths/jbr/hsqldb/db", "ranjith", "sekar");
     statement = connection.createStatement();
     resultSet = statement.executeQuery("SELECT * FROM users");
     while (resultSet.next()) {
       System.out.println("User Name: " + resultSet.getString("FIRST_NAME") \
            + " " + resultSet.getString("LAST_NAME"));
     }
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     try {
       resultSet.close();
       statement.close();
       connection.close();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
}

No comments :

Post a Comment