簡單的JDBC應用程式for Java DB

來源:互聯網
上載者:User

今天下載了jdk1.6.0,以後要慢慢來學習1.6中的新特性和其中的一些經典執行個體。先看看關於java DB的這個最簡例子:
Simple JDBC Application (源碼SimpleApp.java、文檔及derby.jar,derbynet.jar,derbyclient.ar檔案請從jdk1.6.0中找)

這個例子是一個最小限度的JDBC 應用程式。 關於這個程式:

  • 以內嵌式模式(預設的)或作為一個伺服器環境中的用戶端運行,這依賴於傳遞給程式的參數
  • 如果運行在內嵌式模式,則啟動Derby 引擎
  • 如果運行在用戶端模式,則串連到 Derby 網路伺服器
  • 建立並串連到資料庫
  • 建立一個表
  • 插入資料
  • 更新資料
  • 查詢資料
  • 刪除表
  • 關閉串連
  • 如果運行在內嵌式模式,則關閉 Derby。

以下是源碼:

import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;/* * @author janet */public class SimpleApp{    /* 預設的模式是內嵌式的*/    public String framework = "embedded";    public String driver = "org.apache.derby.jdbc.EmbeddedDriver";    public String protocol = "jdbc:derby:";    public static void main(String[] args)    {        new SimpleApp().go(args);    }    void go(String[] args)    {        /* 處理參數,確定這個程式作為內嵌式使用還是作為用戶端使用*/        parseArguments(args);        System.out.println("SimpleApp starting in " + framework + " mode.");        try        {            /*               裝載驅動程式,如果是內嵌式模式,這將啟動Derby, 因為它還沒有運行.             */            Class.forName(driver).newInstance();            System.out.println("Loaded the appropriate driver.");            Connection conn = null;            Properties props = new Properties();            props.put("user", "user1");            props.put("password", "user1");            //create=true將建立資料庫derbyDB            conn = DriverManager.getConnection(protocol +"derbyDB;create=true", props);            System.out.println("Connected to and created database derbyDB");            conn.setAutoCommit(false);//設定自動認可模式            Statement s = conn.createStatement();            /*               建立一個表,加入幾條記錄並更新一條.             */            s.execute("create table derbyDB(num int, addr varchar(40))");            System.out.println("Created table derbyDB");            s.execute("insert into derbyDB values (1956,'Webster St.')");            System.out.println("Inserted 1956 Webster");            s.execute("insert into derbyDB values (1910,'Union St.')");            System.out.println("Inserted 1910 Union");            s.execute(                "update derbyDB set num=180, addr='Grand Ave.' where num=1956");            System.out.println("Updated 1956 Webster to 180 Grand");            s.execute(                "update derbyDB set num=300, addr='Lakeshore Ave.' where num=180");            System.out.println("Updated 180 Grand to 300 Lakeshore");            /*               查詢並校正結果.             */            ResultSet rs = s.executeQuery(                    "SELECT num, addr FROM derbyDB ORDER BY num");            if (!rs.next())            {                throw new Exception("Wrong number of rows");            }            if (rs.getInt(1) != 300)            {                throw new Exception("Wrong row returned");            }            if (!rs.next())            {                throw new Exception("Wrong number of rows");            }            if (rs.getInt(1) != 1910)            {                throw new Exception("Wrong row returned");            }            if (rs.next())            {                throw new Exception("Wrong number of rows");            }            System.out.println("Verified the rows");            s.execute("drop table derbyDB");//刪除表            System.out.println("Dropped table derbyDB");                       rs.close();            s.close();            System.out.println("Closed result set and statement");            conn.commit();            conn.close();            System.out.println("Committed transaction and closed connection");                       boolean gotSQLExc = false;            if (framework.equals("embedded"))            {                try                {                    DriverManager.getConnection("jdbc:derby:;shutdown=true");//關閉資料庫服務                }                catch (SQLException se)                {                    gotSQLExc = true;                }                if (!gotSQLExc)                {                    System.out.println("Database did not shut down normally");                }                else                {                    System.out.println("Database shut down normally");                }            }        }        catch (Throwable e)        {            System.out.println("exception thrown:");            if (e instanceof SQLException)            {                printSQLError((SQLException) e);            }            else            {                e.printStackTrace();            }        }        System.out.println("SimpleApp finished");    }    static void printSQLError(SQLException e)    {        while (e != null)        {            System.out.println(e.toString());            e = e.getNextException();        }    }    private void parseArguments(String[] args)    {       
// System.setProperty("derby.system.home", "c:\\DBdata");//這樣可以設定資料庫資料的存放目錄

int length = args.length; for (int index = 0; index < length; index++) { if (args[index].equalsIgnoreCase("jccjdbcclient")) { framework = "jccjdbc"; driver = "com.ibm.db2.jcc.DB2Driver"; protocol = "jdbc:derby:net://localhost:1527/"; } if (args[index].equalsIgnoreCase("derbyclient")) { framework = "derbyclient"; driver = "org.apache.derby.jdbc.ClientDriver"; protocol = "jdbc:derby://localhost:1527/"; } } }}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.