jdbc操作資料庫基礎
阿新 • • 發佈:2020-12-13
package org.example.jdbc; import java.sql.*; public class FirstExample { // 資料庫資訊 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false"; // 使用者名稱、密碼 static final String USER = "root"; static final String PASS = "jianan"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { // 載入資料庫驅動 Class.forName(JDBC_DRIVER); // 連線資料庫 conn = DriverManager.getConnection(DB_URL, USER, PASS); // 執行sql stmt = conn.createStatement(); String sql = "SELECT id, age, first, last FROM Employees"; rs = stmt.executeQuery(sql); // 遍歷結果集 while (rs.next()) { int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last"); System.out.printf("%d,%d,%s,%s", id, age, first, last); } } catch (Exception e) { e.printStackTrace(); } finally { // 釋放資料庫相關資源 try { if (rs != null) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (stmt != null) { stmt.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } } /* 1,28,賈,楠 2,29,孫,晨曦 */