本文提供一個可重複使用的 JavaBean conndb2005,封裝 SQL Server 2005 的連線管理、查詢執行與參數化新增功能,採用 Microsoft JDBC Driver(com.microsoft.sqlserver.jdbc.SQLServerDriver)。
package test;
import java.sql.*;
import java.io.UnsupportedEncodingException;
public class conndb2005 {
private final String user = "sa";
private final String password = "123";
private final String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private final String url = "jdbc:sqlserver://localhost:1433;DatabaseName=temp";
private Connection conn = null;
private String[] param; // 參數陣列,供 PreparedStatement 使用
public void setParam(String[] param) { this.param = param; }
public conndb2005() {
try { Class.forName(driver); }
catch (ClassNotFoundException e) { System.err.println("驅動程式載入失敗: " + e.getMessage()); }
}
/** 執行查詢,回傳 ResultSet(呼叫端需自行關閉) */
public ResultSet executeQuery(String sql) {
ResultSet rs = null;
try {
conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
} catch (SQLException ex) {
System.err.println("executeQuery 錯誤: " + ex.getMessage());
}
return rs;
}
/** 執行參數化新增/更新/刪除 */
public void insertRecord(String sqlInsert) throws SQLException, UnsupportedEncodingException {
try {
if (conn == null || conn.isClosed()) {
conn = DriverManager.getConnection(url, user, password);
}
PreparedStatement pstmt = conn.prepareStatement(sqlInsert);
if (param != null) {
for (int i = 0; i < param.length; i++) {
pstmt.setString(i + 1, param[i]);
}
}
pstmt.executeUpdate();
pstmt.close();
} catch (SQLException ex) {
System.err.println("insertRecord 錯誤: " + ex.getMessage());
throw ex;
}
}
/** 關閉連線 */
public void close() {
try { if (conn != null && !conn.isClosed()) conn.close(); }
catch (SQLException ignore) {}
}
}
public class TestBean {
public static void main(String[] args) {
conndb2005 db = new conndb2005();
try {
// 查詢
ResultSet rs = db.executeQuery("SELECT * FROM Users");
while (rs.next()) {
System.out.println(rs.getString("UserName"));
}
rs.close();
// 參數化新增
db.setParam(new String[] { "John", "john@example.com", "25" });
db.insertRecord("INSERT INTO Users (Name, Email, Age) VALUES (?, ?, ?)");
System.out.println("新增成功");
} catch (Exception e) { e.printStackTrace(); }
finally { db.close(); }
}
}
| 項目 | 說明 |
|---|---|
| 驅動程式 | Microsoft 官方 Type 4 驅動,無需 ODBC,支援 SQL Server 2005+ |
| 連線管理 | 採用延遲連線,查詢時建立,插入時復用;建議加入連線池(HikariCP) |
| 參數綁定 | 使用 PreparedStatement 防止 SQL 注入,支援批次處理 |
| 資源釋放 | 提供 close(),建議搭配 try-with-resources (Java 7+) |
| 例外處理 | 記錄錯誤並拋出,由上層決定交易回滾或重試 |
application.yml)。HikariDataSource 取代手動 DriverManager.getConnection。sa 帳號,應建立最小權限的應用程式專用帳號。