Saturday 9 November 2013

Java + Apache Derby Database(Embedded Version)

So as many people want to know that How Can We Create JAVA Application which can store data and which can be run on any other computer with JRE without any database configuration once you make it as an executable jar.

Yes, Here I am talking about embedded database with java application.
I am going to use here Derby(Embedded version) very famous database introduced by Apache.

You can find documentation of derby here:Apache Derby

Today we are going to connect pretty simple javaCode with embedded derby database manually with Eclipse so that you can use this code in your any other JAVA application.

I have created one table in embedded derby database inserted some values in that and retrieve it on console.

1) Create Java project.

Java+Embedded Derby

2)Create one java class and add below code in it.As shown in figure.

 package com.demo;  
 import java.sql.Connection;  
 import java.sql.DriverManager;  
 import java.sql.ResultSet;  
 import java.sql.SQLException;  
 import java.sql.Statement;  
 import java.sql.ResultSetMetaData;  
 public class Restaurants  
 {  
   private static String dbURL = "jdbc:derby:myDB;create=true;";  
   private static String tableName = "restaurants";  
   // jdbc Connection  
   private static Connection conn = null;  
   private static Statement stmt = null;  
   public static void main(String[] args)  
   {  
     createConnection();  
     insertRestaurants(5, "LaVals", "Berkeley");  
     selectRestaurants();  
     shutdown();  
   }  
   private static void createConnection()  
   {  
     try  
     {  
       Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();  
       //Get a connection  
       conn = DriverManager.getConnection(dbURL);   
     }  
     catch (Exception except)  
     {  
       except.printStackTrace();  
     }  
   }  
   private static void insertRestaurants(int id, String restName, String cityName)  
   {  
     try  
     {  
       stmt = conn.createStatement();  
       String sql = "CREATE TABLE RESTAURANTS " +  
           "(id INTEGER not NULL, " +  
           " restName VARCHAR(255), " +   
           " cityName VARCHAR(255), " +   
           " PRIMARY KEY ( id ))";   
       stmt.executeUpdate(sql);  
       stmt.execute("insert into " + tableName + " values (" +  
           id + ",'" + restName + "','" + cityName +"')");  
       stmt.close();  
     }  
     catch (SQLException sqlExcept)  
     {  
       sqlExcept.printStackTrace();  
     }  
   }  
   private static void selectRestaurants()  
   {  
     try  
     {  
       stmt = conn.createStatement();  
       ResultSet results = stmt.executeQuery("select * from " + tableName);  
       ResultSetMetaData rsmd = results.getMetaData();  
       int numberCols = rsmd.getColumnCount();  
       for (int i=1; i<=numberCols; i++)  
       {  
         //print Column Names  
         System.out.print(rsmd.getColumnLabel(i)+"\t\t");   
       }  
       System.out.println("\n-------------------------------------------------");  
       while(results.next())  
       {  
         int id = results.getInt(1);  
         String restName = results.getString(2);  
         String cityName = results.getString(3);  
         System.out.println(id + "\t\t" + restName + "\t\t" + cityName);  
       }  
       results.close();  
       stmt.close();  
     }  
     catch (SQLException sqlExcept)  
     {  
       sqlExcept.printStackTrace();  
     }  
   }  
   private static void shutdown()  
   {  
     try  
     {  
       if (stmt != null)  
       {  
         stmt.close();  
       }  
       if (conn != null)  
       {  
         DriverManager.getConnection(dbURL + ";shutdown=true");  
         conn.close();  
       }        
     }  
     catch (SQLException sqlExcept)  
     {  
     }  
   }  
 }  

In this code please note  Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();    as well as  private static String dbURL = "jdbc:derby:myDB;create=true;";  
Which are specific to Embedded derby database if you want to use standalone version of the database then you have to change these lines accordingly.
You can find best information here:Derby dburl and driverstring

3)Put the derby.jar in lib as shown in figure.
You can download derby jar from the Apache derby site that I gave before and please note that for Embedded derby you have to download specific jar.Otherwise you could find ClassNotFoundException :p

And Your Done.:)
Run the code and you will get output on console.

Thanks.GOOD DAY