在編寫JDBC時,用于執行SQL語句時主要涉及到兩個接口。下面我通過執行對數據庫內容的增刪改查來介紹這兩個接口。

Statement接口用于執行靜態 SQL 語句并返回它所生成結果的對象。

在默認情況下,同一時間每個 Statement 對象在只能打開一個 ResultSet 對象。因此,如果讀取一個 ResultSet 對象與讀取另一個交叉,則這兩個對象必須是由不同的 Statement 對象生成的。如果存在某個語句的打開的當前 ResultSet 對象,則 Statement 接口中的所有執行方法都會隱式關閉它。

package com.TinySK;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestStatement {
    // DML數據操作語句--CRUD:create、retrive、update、delete
    // 插入
    public static void testInsert() {
        // DDL數據定義語句
        Connection conn = new ConnectionUtil().openConnection();
        String sql = "insert into CustomerTbl(name,email) values('Michael','michael@java.com')";
        try {
            Statement stmt = conn.createStatement();
            // 執行SQL語句
            stmt.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    conn = null;
                    e.printStackTrace();
                }
        }
    }

    // 更新
    public static void testUpdate() {
        // DDL數據定義語句
        Connection conn = new ConnectionUtil().openConnection();
        String sql = "update CustomerTbl set name='Redking' where id=1";
        try {
            Statement stmt = conn.createStatement();
            // 執行SQL語句
            stmt.executeUpdate(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (conn != null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    conn = null;
                    e.printStackTrace();
                }
        }
    }

    // 刪除
    public static void testDelete() {
        // DDL數據定義語句
        Connection conn = new ConnectionUtil().openConnection();
        String sql = "delete from CustomerTbl";
        try {
            Statement stmt = conn.createStatement();
            // 執行SQL語句
            stmt.executeUpdate(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (conn != null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    conn = null;
                    e.printStackTrace();
                }
        }
    }

    // 查詢
    public static void testQuery() {
        // DDL數據定義語句
        Connection conn = new ConnectionUtil().openConnection();
        String sql = "select * from CustomerTbl";
        try {
            Statement stmt = conn.createStatement();
            // 執行SQL語句
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                // 可以通過列索引
                int id = rs.getInt(1);
                // 可以通過列名稱
                String name = rs.getString("name");
                String email = rs.getString(3);
                System.out.println(id + ":" + name + ":" + email);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (conn != null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    conn = null;
                    e.printStackTrace();
                }
        }
    }
}

PreparedStatement表示預編譯的 SQL 語句的對象。

SQL 語句被預編譯并存儲在 PreparedStatement 對象中。然后可以使用此對象多次高效地執行該語句。

注:用于設置 IN 參數值的設置方法(setShortsetString 等等)必須指定與輸入參數的已定義 SQL 類型兼容的類型。例如,如果 IN 參數具有 SQL 類型 INTEGER,那么應該使用 setInt 方法。

如果需要任意參數類型轉換,使用 setObject 方法時應該將目標 SQL 類型作為其參數。

package com.TinySK;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class TestPrepareStatement {
    //查詢
    public static List<Customer> query(String name){
         Connection conn = new ConnectionUtil().openConnection();
         String sql = "select * from CustomerTbl where name = ?";
         try{
             PreparedStatement pstmt = conn.prepareStatement(sql);
             pstmt.setString(1, name);
             ResultSet rs = pstmt.executeQuery();
             List<Customer> list = new ArrayList<Customer>();
             while(rs.next()){
                 int id = rs.getInt(1);
                 String email = rs.getString(3);
                 Customer c = new Customer();
                 c.setId(id);
                 c.setName(name);
                 c.setEmail(email);
                 list.add(c);
             }
             System.out.println(list.size());
             return list;
         }catch (SQLException e){
             e.printStackTrace();
         }
       return null;
     }
    //添加
    public static void add(Customer c){
        Connection conn = new ConnectionUtil().openConnection();
        String sql = "insert into CustomerTbl(name,email) values(?,?)";
        try{
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, c.getName());
            pstmt.setString(2, c.getEmail());
            pstmt.executeUpdate();
        }catch(SQLException e){
            e.printStackTrace();
        }
    }
    //刪除
    public static void delete(int id){
        Connection conn = new ConnectionUtil().openConnection();
        String sql = "delete from CustomerTbl where Id = ?";
        try{
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            pstmt.executeUpdate();
        }catch(SQLException e){
            e.printStackTrace();
        }
    }
    //更新
    public static void update(String name1,String name2){
        Connection conn = new ConnectionUtil().openConnection();
        String sql = "update CustomerTbl set name = ? where name = ?";
        try{
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, name1);
            pstmt.setString(2, name2);
            pstmt.executeUpdate();
        }catch(SQLException e){
            e.printStackTrace();
        }
    }
  }
}

有關Statement與PreparedStatement接口中的方法還有很多種,隨程序功能的不同使用它們的地方也不同,但總的來說,PreparedStatement比較靈活,建議大家查詢JDK-API,對PreparedStatement接口所涉及的方法多加留意,這樣在使用時會給編程帶來不少的便利。