1. 程式人生 > 其它 >使用JDBC第一次嘗試與本地資料庫連接獲取查詢結果並輸出

使用JDBC第一次嘗試與本地資料庫連接獲取查詢結果並輸出

技術標籤:資料庫mysqljavajdbc

package com.wt.firsttset;
import java.sql.*;

import java.sql.Connection;
import java.sql.DriverManager;

public class MyFirstJDBCTest {
public static void main(String[] args) throws ClassNotFoundException,SQLException{
//1.載入驅動
//Class.forName(“com.mysql.jdbc.Driver”);固定寫法,載入資料庫驅動。將此句註釋前執行時提醒The new driver class is `com.mysql.cj.jdbc.Driver’並且提醒這是自動完成的,不需要手動載入

    //2.連線資料庫,提供資料庫的url,向mysql提供使用者資訊
    String url = "jdbc:mysql://localhost:3306/schoola?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTC";
    //jdbc:mysql://localhost:3306/schoola 連線本地資料庫schoola埠號3306
    //?useUnicode=true&characterEncoding=utf8&useSSL=true
    //useUnicode=true 使支援中文
    //characterEncoding=utf8 將中文字符集編碼設定為utf8
    //useSSL=true 使用SSL安全連線,防止一些錯誤
    //serverTimezone=UTC 執行報錯,提示時區問題,設定為UTC(統一標準世界時間)後解決
    String username = "root";//登入賬戶
    String password = "root";//登入密碼

    //3.用2中的三個東西連線mysql,獲取資料庫物件
    Connection connection = DriverManager.getConnection(url,username,password);
    //Connection代表資料庫

    //4.建立執行sql的物件,用此物件來處理sql語句
    Statement statement = connection.createStatement();

    //5.用執行sql的物件去執行sql語句,這裡測試一個查詢語句,可以得到結果,檢視返回結果
    String sql = "select * from student";//宣告一個變數存放sal語句
    ResultSet resultSet = statement.executeQuery(sql);
    //statement.executeQuery(sql)代表將變數名為sql查詢語句執行,這句查詢語句有返回結果,將結果放在結果集resultSet裡
    //statement.execute();可以執行所有的sql語句,因為有個判斷是什麼sql語句的過程,執行效率稍微低一點
    //statement.executeQuery();只能執行sql查詢語句
    //statement.executeUpdate();只能執行sql增改刪語句 注意:增改刪全部用executeUpdate
    //結果集resultSet中封裝了查詢出的全部結果,resultSet只有查詢才有,因為只有查詢才會出結果
    while(resultSet.next()){//用next遍歷,resultSet.next()代表移動到下一個資料(一個數據就是一行、一個記錄)
        System.out.print("id"+resultSet.getObject("id"));
        System.out.print(" name"+resultSet.getObject("name"));
        System.out.print(" sex"+resultSet.getObject("sex"));
        System.out.println(" age"+resultSet.getObject("age"));
        System.out.println("---------------------");
    }//將結果集中的內容輸出
    //resultSet.getObject();在列(屬性)型別不知道時使用,知道屬性就不建議使用,知道型別時使用下面的

// resultSet.getInt();
// resultSet.getString();
// resultSet.getFloat();等等

    //6.操作完成,釋放連線
    resultSet.close();
    statement.close();
    connection.close();
}

}