Java/JDK 6/Java DB Derby

Материал из Java эксперт
Перейти к: навигация, поиск

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();
    }
  }
}





Derby ISQL

Derby JDBC Connection

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class MainClass {
   public static void main(String[] args)
   {
      try {
         String driver = "org.apache.derby.jdbc.EmbeddedDriver";
         Class.forName(driver).newInstance();
         Connection conn = null;
         conn = DriverManager.getConnection("jdbc:derby:DerbyTestDB");
         Statement s = conn.createStatement();
         ResultSet rs = s.executeQuery("SELECT city, state, zipcode FROM zipcodes");
         while(rs.next()) {
            System.out.println("City   : "+ rs.getString(1));
            System.out.println("State  : "+ rs.getString(2));
            System.out.println("Zipcode: "+ rs.getString(3));
            System.out.println();
         }
         rs.close();
         s.close();
         conn.close();
      } catch(Exception e) {
         System.out.println("Exception: "+ e);
         e.printStackTrace();
      }
   }
}