[Database] Derby使用筆記

  • Starts up the Derby engine

    Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();

  • Creates and connects to a database

    Connection conn = DriverManager.getConnection("jdbc:derby:" + dbName + ";create=true");

    // 若要自行手動控制transaction, 要將JDBC中預設的autocommit功能關掉.
    conn.setAutoCommit(false);

  • Creates a table

    // 可針對該資料庫重複使用的Statement物件
    Statement stmt = conn.createStatement();
    // 建立名為location的資料表
    stmt.execute("CREATE TABLE location(num int, addr varchar(40))");

  • Inserts data

    // 當重覆執行SQL敘述時, 建議使用PreparedSstatement(可以不需要每次都recompileSQL敘述)
    PreparedStatement pStmt = conn.prepareStatement("INSERT INTO location VALUES(?, ?)");
    pStmt.setInt(1, 1956);
    pStmt.setString(2, "Min-Sheng East Road");
    pStmt.executeUpdate();

  • Updates data

    PreparedStatement psUpdate = conn.prepareStatement("UPDATE location SET num=?, addr=? where num=?");
    psUpdate.setInt(1, 300);
    psUpdate.setString(2, "Cheng-Guong Road Section 1");
    psUpdate.setInt(3, 1956);
    psUpdate.executeUpdate();

  • Selects data

    ResultSet rs = stmt.executeQuery("SELECT num, addr FROM location ORDER BY num");
    while(rs.next())
    {
    // do something with the result set
    }

  • Drops a table

    stmt.execute("DROP TABLE location");

  • Disconnects

    if(conn != null)
    {
    conn.close();
    conn = null;
    }

  • Shuts down Derby

    // 在embedded mode下, application應該負責關閉資料庫.
    // 建議使用連接的URL來明確關閉資料庫, 雖然此做法必定會丟出SQLException.
    try
    {
    // 如要關閉Derby引擎, 則不能指定資料庫名稱
    DriverManager.getConnection("jdbc:derby:;shutdown=true");

    // 如只要關閉某個資料庫, 而不停止Derby引擎, 則必須指定要關閉的資料庫名稱
    DriverManager.getConnection("jdbc:derby:" + dbName + ";shutdown=true");
    }
    catch (SQLException se)
    {
    if (( (se.getErrorCode() == 50000) && ("XJ015".equals(se.getSQLState()) ))) {
    // we got the expected exception
    System.out.println("Derby shut down normally");
    // Note that for single database shutdown, the expected
    // SQL state is "08006", and the error code is 45000.
    } else {
    // if the error code or SQLState is different, we have
    // an unexpected exception (shutdown failed)
    System.err.println("Derby did not shut down normally");
    // 需額外處理
    }
    }

留言

這個網誌中的熱門文章

PHP:callback函數的使用

PHP:變數範圍

PHP常用函數:陣列(array)