天天看點

【Java】JDBC資料庫開發入門

JDBC是什麼:

JDBC(Java DataBase Connectivity,Java資料庫連接配接)是一種用于執行SQL語句的Java API,可以為多種關系資料庫提供統一通路,它由一組用Java語言編寫的類和接口組成。JDBC提供了一種基準,據此可以建構更進階的工具和接口,使資料庫開發人員能夠編寫資料庫應用程式。

想學會使用Java連接配接并操作資料庫:JDBC資料庫開發入門

資料庫驅動:

我們安裝好資料庫之後,我們的應用程式也是不能直接使用資料庫的,必須要通過相應的資料庫驅動程式,通過驅動程式去和資料庫打交道。其實也就是資料庫廠商的JDBC接口實作,即對Connection等接口的實作類的jar檔案。

【Java】JDBC資料庫開發入門

JDBC常用接口:

1.Driver接口

  Driver接口由資料庫廠家提供,作為java開發人員,隻需要使用Driver接口就可以了。在程式設計中要連接配接資料庫,必須先裝載特定廠商的資料庫驅動程式,不同的資料庫有不同的裝載方法。如:

  裝載MySql驅動:Class.forName("com.mysql.jdbc.Driver");

  裝載Oracle驅動:Class.forName("oracle.jdbc.driver.OracleDriver");

2.Connection接口

  Connection與特定資料庫的連接配接(會話),在連接配接上下文中執行sql語句并傳回結果。DriverManager.getConnection(url, user, password)方法建立在JDBC URL中定義的資料庫Connection連接配接上。

  連接配接MySql資料庫:Connection conn = DriverManager.getConnection("jdbc:mysql://host:port/database", "user", "password");

  連接配接Oracle資料庫:Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@host:port:database", "user", "password");

  連接配接SqlServer資料庫:Connection conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://host:port; DatabaseName=database", "user", "password");

  常用方法:

    • createStatement():建立向資料庫發送sql的statement對象。
    • prepareStatement(sql) :建立向資料庫發送預編譯sql的PrepareSatement對象。
    • prepareCall(sql):建立執行存儲過程的callableStatement對象。
    • setAutoCommit(boolean autoCommit):設定事務是否自動送出。
    • commit() :在連結上送出事務。
    • rollback() :在此連結上復原事務。

3.Statement接口

  用于執行靜态SQL語句并傳回它所生成結果的對象。

  三種Statement類:

    • Statement:由createStatement建立,用于發送簡單的SQL語句(不帶參數)。
    • PreparedStatement :繼承自Statement接口,由preparedStatement建立,用于發送含有一個或多個參數的SQL語句。PreparedStatement對象比Statement對象的效率更高,并且可以防止SQL注入,是以我們一般都使用PreparedStatement。
    • CallableStatement:繼承自PreparedStatement接口,由方法prepareCall建立,用于調用存儲過程。

  常用Statement方法:

    • execute(String sql):運作語句,傳回是否有結果集
    • executeQuery(String sql):運作select語句,傳回ResultSet結果集。
    • executeUpdate(String sql):運作insert/update/delete操作,傳回更新的行數。
    • addBatch(String sql) :把多條sql語句放到一個批進行中。
    • executeBatch():向資料庫發送一批sql語句執行。

4.ResultSet接口

  ResultSet提供檢索不同類型字段的方法,常用的有:

    • getString(int index)、getString(String columnName):獲得在資料庫裡是varchar、char等類型的資料對象。
    • getFloat(int index)、getFloat(String columnName):獲得在資料庫裡是Float類型的資料對象。
    • getDate(int index)、getDate(String columnName):獲得在資料庫裡是Date類型的資料。
    • getBoolean(int index)、getBoolean(String columnName):獲得在資料庫裡是Boolean類型的資料。
    • getObject(int index)、getObject(String columnName):擷取在資料庫裡任意類型的資料。

  ResultSet還提供了對結果集進行滾動的方法:

    • next():移動到下一行
    • Previous():移動到前一行
    • absolute(int row):移動到指定行
    • beforeFirst():移動resultSet的最前面。
    • afterLast() :移動到resultSet的最後面。

使用後依次關閉對象及連接配接:ResultSet → Statement → Connection

更多精品技術課程:

阿裡雲大學官網(阿裡雲大學 - 官方網站,雲生态下的創新人才工場)