JDBC(Java Database Connectivity) 是 Java 執行 SQL 的標準 API,提供統一介面存取多種關聯式資料庫。其優點:
package DAO;
import java.sql.*;
import java.util.*;
public class JDBC {
protected Connection conn;
protected Statement statement;
// 取得資料庫連線
public static Connection getConnection() throws Exception {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver"); // 載入驅動
// 127.0.0.1:3306/test 為本地資料庫,user/password 請自行修改
connection = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/test", "user", "password");
} catch (Exception e) {
e.printStackTrace();
throw new Exception("連線 MySQL 失敗");
}
return connection;
}
// 新增資料
public int insert(String sql) throws Exception {
conn = getConnection();
try {
statement = (Statement) conn.createStatement();
int count = statement.executeUpdate(sql);
conn.close();
return count;
} catch (SQLException e) {
e.printStackTrace();
throw new Exception("新增資料失敗");
}
}
// 更新資料
public int update(String sql) throws Exception {
conn = getConnection();
try {
statement = (Statement) conn.createStatement();
int count = statement.executeUpdate(sql);
conn.close();
return count;
} catch (SQLException e) {
e.printStackTrace();
throw new Exception("更新資料失敗");
}
}
// 查詢資料,回傳 List<Map>
public List<Object> query(String sql) throws Exception {
conn = getConnection();
try {
statement = (Statement) conn.createStatement();
ResultSet rs = statement.executeQuery(sql);
List<Object> list = ResultSetToList(rs);
conn.close();
return list;
} catch (SQLException e) {
e.printStackTrace();
throw new Exception("查詢資料失敗");
}
}
// 刪除資料
public int delete(String sql) throws Exception {
conn = getConnection();
try {
statement = (Statement) conn.createStatement();
int count = statement.executeUpdate(sql);
conn.close();
return count;
} catch (SQLException e) {
e.printStackTrace();
throw new Exception("刪除資料失敗");
}
}
// 分頁查詢
public List<Object> findByPage(String sql, int page, int count) throws Exception {
conn = getConnection();
PreparedStatement pre = conn.prepareStatement(sql);
pre.setMaxRows(count);
ResultSet rs = pre.executeQuery();
if (page < 1) rs.absolute(0);
else {
page = page * count - 1;
rs.absolute(page);
}
List<Object> list = ResultSetToList(rs);
return list;
}
// ResultSet 轉 List<Map>
public List<Object> ResultSetToList(ResultSet rs) throws SQLException {
if (rs == null) return Collections.emptyList();
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
List<Object> list = new ArrayList<>();
while (rs.next()) {
Map<Object, Object> rowData = new HashMap<>(columnCount);
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnName(i), rs.getObject(i));
}
list.add(rowData);
}
return list;
}
}
Class.forName("com.mysql.jdbc.Driver");Connection conn = DriverManager.getConnection(url, user, pass);Statement stmt = conn.createStatement();ResultSet rs = stmt.executeQuery("SELECT * FROM user");rs.next() 讀取欄位值。rs、stmt、conn。PreparedStatement 防止 SQL 注入。finally 區塊或使用 try-with-resources (Java 7+)。