Apache derby(JavaDB)

Započeo maxogm, 26.12.2010, 23:20

prethodna tema - sledeća tema

maxogm

Primer rada sa derby(JavaDB) embedded bazom podataka.

Primer jedne tabele u derby bazi podataka

CREATE
    TABLE TBL_USER
    (
        ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
        FIRST_NAME VARCHAR(128) NOT NULL,
        LAST_NAME VARCHAR(128) NOT NULL,
        PRIMARY KEY (ID)
    )


Za vasu aplikaciju potreban vam je samo derby jar. Mozete ga preuzeti lako koristeci maven2.

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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Derby</groupId>
  <artifactId>Derby</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
      <groupId>org.apache.derby</groupId>
      <artifactId>derby</artifactId>
      <version>10.5.3.0_1</version>
    </dependency>
  </dependencies>
</project>


Primer jedne klase za rad sa bazom:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author vladem
*/
public class EmbeddedDerby
{

   private String dbPath = "d:/myJavaDB";

   public EmbeddedDerby()
   {
      Connection conn = null;
      try
      {
         Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
         conn = DriverManager.getConnection("jdbc:derby:" + dbPath + ";create=false", "admin", "admin");
         Statement query = conn.createStatement();

         query.execute("INSERT INTO TBL_USER (first_name, last_name) VALUES ('Vlade', 'Maksimovic')");
         // displaying record
         ResultSet rs = query.executeQuery("SELECT * FROM TBL_USER");
         while (rs.next())
         {
            System.out.println("ID: " + rs.getInt("id") + "; First name: "
                  + rs.getString("first_name") + "; Last name: "
                  + rs.getString("last_name"));
         }
      } catch (Exception ex)
      {
         Logger.getLogger(EmbeddedDerby.class.getName()).log(Level.SEVERE, null, ex);
      } finally{
        try
      {
         conn.close();
      } catch (SQLException e)
      {
         e.printStackTrace();
      }
      }
   }

   public static void main(String... args)
   {
      new EmbeddedDerby();
   }
}