1. 程式人生 > >JDBC程式設計

JDBC程式設計

一、最簡單的流程

  • 載入相應的資料庫驅動
  • 通過DriverManger獲取Connection
  • 通過Connection獲取PrepareStatement,並設定查詢語句
  • 通過PrepareStatement執行sql語句
  • 通過ResultSet獲取查詢結果

例子:

import java.sql.*;

public class Main {

    public static void main(String[] args) {
        System.out.println("打印出test資料庫中的user表資料");
        //1.載入資料庫驅動
        try
{ Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("沒有找到mysql資料庫驅動!!!"); e.printStackTrace(); System.exit(0); } //2.獲取連線 Connection conn; try { conn = DriverManager.
getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "root", "root"); //3.獲取PrepareStatement物件,並傳入查詢語句 PreparedStatement ps = conn.prepareStatement("SELECT * FROM user "); //4.執行PrepareStatement物件 ResultSet resultSet = ps.executeQuery(); //5.用遊標輸出結果
while (resultSet.next()) { System.out.print("id:" + resultSet.getInt(1)); System.out.print(" username:" + resultSet.getString(2)); System.out.println(" age:" + resultSet.getInt(3)); } } catch (SQLException e) { e.printStackTrace(); System.exit(0); } } }

執行結果: 在這裡插入圖片描述

二、常用介面(還真是Interface)

介面 說明
DriverManger 資料庫驅動程式,用於連線jdbc和對應資料庫
Connection 用於建立一個數據庫連線,要想訪問資料庫,就得先獲取資料庫連線。通過DrverManger.getConnection()獲取連線
PrepareStatement 預編譯的Statement物件,只有更改sql引數就行。通過ConnectionInstance.prepareStatement()獲取。
ResultSet 結果集物件。可以同PrepareStatementInstance.executeQuery()返回

三、執行SQL語句的幾種方式

方式 說明
execute() 此方法的返回值是boolean,表示是否返回ResulSet物件。若是,可以通過getResultSet()獲取。
executeUpate() 返回受影響的行數。
executeLargeUpdate() 和executeUpdate()差不多,只是當受影響的數目非常大時(推薦使用executeLargerUpdate())
executeQuery() 只能執行查詢語句,返回ResultSet

上面方法時Statement的,當然PrepareStatement也提供了這些方法。但使用Statement和PrepareStatement的區別:

  1. PrepareStatement預編譯SQL語句,效能更好
  2. PrepareStatement不用拼接sql語句,程式設計更簡單
  3. PrepareStatement可以防止SQL注入(2就是原因),更safe。

ResultSet管理結果集

RowSet管理結國集和分析結果集

事務管理與批量更新

分析資料庫資訊

使用連線池管理連線