封裝 JDBC 重複代碼,提供增刪改查通用方法,使用 PreparedStatement 防 SQL 注入,finally 保證資源釋放。
package dao;
import java.sql.*;
public class BaseDao {
private String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private String url = "jdbc:sqlserver://localhost:1433;DatabaseName=BookManage";
private String user = "sa";
private String password = "";
protected Connection conn;
protected PreparedStatement ps;
protected ResultSet rs;
/** 取得連線 */
public Connection getCon() {
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return conn;
}
/** 統一關閉資源(逆序:ResultSet → Statement → Connection) */
public void closeAll(ResultSet rs, PreparedStatement ps, Connection conn) {
try {
if (rs != null) rs.close();
if (ps != null) ps.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
/** 通用增刪改:支援可變參數綁定 */
public int executeUpdate(String sql, Object... params) {
int rows = 0;
try {
ps = getCon().prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
}
rows = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeAll(rs, ps, conn);
}
return rows;
}
/** 通用查詢單筆(範例擴充) */
public T queryForObject(String sql, RowMapper mapper, Object... params) {
try {
ps = getCon().prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) ps.setObject(i + 1, params[i]);
}
rs = ps.executeQuery();
if (rs.next()) return mapper.mapRow(rs);
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeAll(rs, ps, conn);
}
return null;
}
/** 介面:ResultSet → 物件映射 */
public interface RowMapper {
T mapRow(ResultSet rs) throws SQLException;
}
}
public class UserDao extends BaseDao {
public int add(User u) {
return executeUpdate(
"INSERT INTO t_user(username, password, email) VALUES(?,?,?)",
u.getUsername(), u.getPassword(), u.getEmail()
);
}
public User findById(int id) {
return queryForObject("SELECT * FROM t_user WHERE id=?", rs -> {
User u = new User();
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
return u;
}, id);
}
}
conn.setAutoCommit(false)、commit/rollbackJdbcTemplate 或 MyBatis 替代手寫 DAO