Monday, January 05, 2009

HSQLDB

HSQLDB is a 100% Java database which is embeddable. It has a small footprint and can be used for self-contained applications. The source files, the JAR file and support documents can be downloaded from hsqldb.org. It also provides a JDBC driver. HSQLDB is perfect for quick implementation and testing.

Following is a sample program which uses the JDBC driver for creating a table, inserting some data in the table and listing the rows from the table:

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.PreparedStatement;

public class HSQLTest {
Connection conn;
Statement stmt;
PreparedStatement add_stmt, get_stmt;

static {
try{
Class.forName("org.hsqldb.jdbcDriver").newInstance();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
catch(InstantiationException e) {
e.printStackTrace();
}
catch(IllegalAccessException e) {
e.printStackTrace();
}
}

HSQLTest() {
try {
initializeDB();
createTable();
populateTable();
displayRows();
}
catch(SQLException e) {
e.printStackTrace();
}
}

void initializeDB() throws SQLException {
conn = DriverManager.getConnection("jdbc:hsqldb:db/test", "sa", "");
stmt = conn.createStatement();
}

public void createTable() throws SQLException {
String table_name = "sample_table";
DatabaseMetaData dbM = conn.getMetaData();
ResultSet rs = dbM.getTables(null, null, "%", null);
boolean found = false;
while(rs.next()) {
String s = rs.getString(3);
//System.out.println(s);
if(s.equalsIgnoreCase(table_name)) {
found = true;
break;
}
}

if(!found) {
String s = "CREATE TABLE " + table_name + "(id INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1000) PRIMARY KEY, " +
"category VARCHAR(40), name VARCHAR(40))";
stmt.execute("SET WRITE_DELAY FALSE;");
stmt.executeUpdate(s);
}
}

public void populateTable() throws SQLException {
stmt.executeUpdate("insert into SAMPLE_TABLE (category, name) values ('E0', 'Ben')");
}

public void displayRows() throws SQLException {
ResultSet rs = stmt.executeQuery("SELECT * FROM SAMPLE_TABLE");
int numCols = rs.getMetaData().getColumnCount();
while(rs.next()) {
for(int i=1; i<=numCols; i++) {
System.out.println(rs.getString(i) + ": " + rs.getString(i));
}
}
}

public static void main(String[] args) {
HSQLTest hTest = new HSQLTest();
}
}

No comments: