Java Tutorial/Database/Java DB Derby

Материал из Java эксперт
Версия от 05:06, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Connect to Derby database

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class MainClass {
  static Connection conn;
  public static void main(String[] args) throws Exception {
    if (args.length != 2) {
      System.out.println("Usage: java JavaDBDemo <Name> <Address>");
      System.exit(1);
    }
    String driver = "org.apache.derby.jdbc.EmbeddedDriver";
    String dbName = "AddressBookDB";
    String connectionURL = "jdbc:derby:" + dbName + ";create=true";
    String createString = "CREATE TABLE ADDRESSBOOKTbl (NAME VARCHAR(32) NOT NULL, ADDRESS VARCHAR(50) NOT NULL)";
    Class.forName(driver);
    conn = DriverManager.getConnection(connectionURL);
    Statement stmt = conn.createStatement();
    stmt.executeUpdate(createString);
    PreparedStatement psInsert = conn
        .prepareStatement("insert into ADDRESSBOOKTbl values (?,?)");
    psInsert.setString(1, args[0]);
    psInsert.setString(2, args[1]);
    psInsert.executeUpdate();
    Statement stmt2 = conn.createStatement();
    ResultSet rs = stmt2.executeQuery("select * from ADDRESSBOOKTbl");
    System.out.println("Addressed present in your Address Book\n\n");
    int num = 0;
    while (rs.next()) {
      System.out.println(++num + ": Name: " + rs.getString(1) + "\n Address"
          + rs.getString(2));
    }
    rs.close();
  }
}





Connect to Java DB (Derby) with org.apache.derby.jdbc.EmbeddedDriver

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class JavaDBDemo {
  static Connection conn;
  public static void main(String[] args) {
    String driver = "org.apache.derby.jdbc.EmbeddedDriver";
    String connectionURL = "jdbc:derby:myDatabase;create=true";
    String createString = "CREATE TABLE Employee (NAME VARCHAR(32) NOT NULL, ADDRESS VARCHAR(50) NOT NULL)";
    try {
      Class.forName(driver);
    } catch (java.lang.ClassNotFoundException e) {
      e.printStackTrace();
    }
    try {
      conn = DriverManager.getConnection(connectionURL);
      Statement stmt = conn.createStatement();
      stmt.executeUpdate(createString);
      PreparedStatement psInsert = conn.prepareStatement("insert into Employee values (?,?)");
      psInsert.setString(1, args[0]);
      psInsert.setString(2, args[1]);
      psInsert.executeUpdate();
      Statement stmt2 = conn.createStatement();
      ResultSet rs = stmt2.executeQuery("select * from Employee");
      int num = 0;
      while (rs.next()) {
        System.out.println(++num + ": Name: " + rs.getString(1) + "\n Address" + rs.getString(2));
      }
      rs.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}





JavaDB Drivers

Based on the environment in which JavaDB is running, Java SE 6 contains two drivers for accessing JavaDB. They are:

Embedded driver enables you to access JavaDB databases running in the embedded environment.

The org.apache.derby.jdbc.EmbeddedDriver class implements the embedded driver.

Network client driver enables you to access the JavaDB database running in the client/server environment.

The org.apache.derby.jdbc.ClientDriver class implements the network client driver.


JavaDB Tools

Java SE 6 contains various tools that you can use to start, stop, access, and administer JavaDB.

Some of the JavaDB tools are:

  1. server: Starts the JavaDB database.
  2. ij Represents a JDBC scripting tool.
  3. You can use ij to run scripts against a JavaDB database.
  4. You can also use ij to run SQL queries.
  5. You can use ij to access JavaDB running in both the embedded and client/server environments.
  6. sysinfo: Displays information about the JavaDB version and the environment.
  7. dblook: Generates and stores the Data Definition Language (DDL) to a file.
  8. In Java SE 6, the server, ij, sysinfo, and dblook tools are packaged in the derbyrun.jar file.
  9. You can locate the derbyrun.jar file in the <JAVA_HOME>/db/lib directory.


JavaDB URLs

To connect to an existing JavaDB database using the embedded driver:



jdbc:derby:<databaseName>;<URLAttributes>



  1. host: Specifies the computer name or Internet Protocol address where Java DB is running. If Java DB is running on the same computer as that of the client, you can use localhost or 127.0.0.1 as the value of the host option.
  2. Port: Specifies the port number used by JavaDB to accept incoming requests.
  3. databaseName: Represents the name of the database to connect with.


New to Java 6 is a lightweight database called Derby.

Derby is a product of the Apache Database project.

Derby is a transactional, relational database.

Derby provides a small footprint on disk.

Deployment is much easier because Derby supports storage of a database archived in a JAR file.

Derby allows you to simply distribute the JAR file.


Ping JavaDB.

The command to ping JavaDB is:



java �jar derbyrun.jar server ping
java �jar derbyrun.jar server ping 192.168.0.1 1555





The JavaDB Directory Structure

When you install Java SE 6, JavaDB installs in the db directory of JAVA_HOME.

The db directory contains the following subdirectories:

  1. demo: Contains sample programs and scripts to use JavaDB.
  2. lib: Contains the JavaDB JAR files. You need to use the JavaDB JAR files to start, stop, and access JavaDB.
  3. frameworks: Contains scripts for setting up the environment to use JavaDB in different environments.


The JavaDB Environments

Embedded: Allows only a single application to access a database at one time.

In the embedded environment, no network access occurs.

When you load a JDBC driver from a Java program, JavaDB automatically starts in the embedded environment.

Client/server: Allows multiple applications to connect to JavaDB over the network.

To start JavaDB in the client/server environment, you need to use the server command line tool of JavaDB.


The SQL script for creating the Employee Table

CREATE TABLE Employee (
    Employee_ID int NOT NULL,
    NAME        varchar (50) NOT NULL,
    DESCRIPTION varchar (250) NOT NULL
)
////////////////////////////////////////////////////////
public class Employee {
    public int employeeId;
    public String name;
    public String description;

    public String toString () {
        StringBuilder buf = new StringBuilder ();
        buf.append ("\n\tEmployee ID = ") .append (employeeId);
        buf.append ("\n\tName = ").append (name);
        buf.append ("\n\tDescription = ").append (description);
        return buf.toString ();
     }
}
///////////////////////////////////////////////////////
import java.sql.BaseQuery;
import java.sql.DataSet;
import java.sql.Select;
public interface EmployeeQueries extends BaseQuery {
    // Select all employees
    @Select (sql = "SELECT Employee_ID, NAME, DESCRIPTION FROM Employee", readOnly=false, connected=false)
    DataSet<Employee> getAllEmployees();
    // Select employee by name
    @Select ("SELECT Employee_ID, NAME, DESCRIPTION FROM Employee where NAME = ?")
    DataSet<Employee> getEmployeeByName(String name);
}

import java.sql.Connection;
import java.sql.DataSet;
import java.sql.DriverManager;
import java.sql.SQLException;
public class QueryDemo {
    public static void main (String [] args) {
        Connection connection = null;
        try {
            String url = "jdbc:inetdae7:localhost:1433?database=Adaptor";
            String login = "sa";
            String password "admin";
            connection = DriverManager.getConnection(url, login,password);
            EmployeeQueries qo = connection.createQueryObject(EmployeeQueries.class); 
            // Get all employees
            DataSet<Employee> rows = qo.getAllEmployees ();
            for (Employee employee : rows) {
                System.out.println (employee);
            }
            // Create new Employee object
            if (! rows.isReadOnly () ) {
                System.out.printIn ("\nCreate new employee");
                Employee r = new Employee ();
                r.Employee_ID = 12345;
                r.name = "Supervisor";
                r.description = "Do monitoring job";
                boolean insertResult = rows. insert (r);
                rows.sync (connection);
                System.out.println ("\tInserted: " + insertResult);
          }
          // Retrieve Employee by name
          System.out.println ("\nGet employee by name:");
          DataSet<Employee> rows2 = qo.getEmployeeByName ("Supervisor");
          Employee employee = rows2.get (0);
          System.out.println (Employee);
          if (Employee != null) {
              // Modify Role
              System.out.println ("\nModify current Employee:");
              employee.description = "Do supervising job";
              boolean modifyResult = rows2.modify (employee);
              rows2.sync (connection);
              System.out.println ("\tModified: " + modifyResult);
          }
      } catch (SQLException e) {
          for (Throwable t : e) {
               t.printStackTrace ();
          }
       } finally {
            // Close connection
            try {
                connection.close ();
            } catch (SQLException e) {
                e.printStackTrace ();
            } 
         }
    }
}





To stop JavaDB, you can use the following command:

java �jar derbyrun.jar server shutdown





To view run time information for JavaDB, you can use the following command:

java �jar derbyrun.jar server runtime





To view the structure of the Employee table

Describe Employee;





Using the ij Tool

The ij tool enables you to connect to a running JavaDB server and execute scripts and queries against a database.

The command to use the ij tool is:



java �jar derbyrun.jar ij



Commands of the ij Tool

CommandDescriptionDriverLoads the specified JDBC driver.ProtocolSets the specified protocol to use for connecting to a database.ConnectEstablishes a connection with a database.Set ConnectionSwitches from the existing connection to a different connection specified with a connection name.Show ConnectionsLists all active connections.DisconnectDisconnects the current connection, a connection specified by a connection name, or all active connections.Show SchemasLists all schemas present in the current database.Show TablesLists all tables present in the current database.Show ViewsLists all views present in the current database.Show ProceduresLists all stored procedures present in the current database.Show IndexesLists all indexes present in a specified table.DescribeDisplays information about columns, such as column name and data type, for a specified table.rumitCommits the current transaction.RollbackRolls back the current transaction.


Using the sysinfo Tool

The code to run the sysinfo tool is:



java -jar derbyrun.jar sysinfo





Viewing and Switching Connections

Show Connections command lists the active connections established with JavaDB.

You can then use the Set connection command to switch to a different connection.

To view and switch between connections:



show connections;





Working with Tables

Use the Create Table SQL command to create a new table in a database.



Create table employee (name varchar(30),address varchar(50));





You can use the connect command of ij to establish a connection with a database

The connect command loads a JDBC driver to establish the connection.

The command to establish a connection with a sample database is:



connect "jdbc:derby:sample";





You can use the server tool to start JavaDB in a network client environment.

To start JavaDB:

Set the Path environment variable to include the <JAVA_HOME>/db/lib directory.

Open the command prompt and type the following command:



java �jar derbyrun.jar server start