public class JdbcUtil {
private static final Properties ps = new Properties();
private JdbcUtil() {
}
static {
loadProperties();
}
private static void loadProperties() {
try {
InputStream is = JdbcUtil.class.getResourceAsStream("jdbc.properties");
ps.load(is);
String driverName = ps.getProperty("driver", "com.mysql.cj.jdbc.Driver");
Class.forName(driverName);
} catch (Exception e) {
ps.setProperty("driver", "com.mysql.cj.jdbc.Driver");
ps.setProperty("url", "jdbc:mysql://localhost:3306/test?serverTimezone=UTC");
ps.setProperty("username", "root");
ps.setProperty("password", "123456");
}
}
public static Connection getConnection() throws Exception {
if (ps.size() > 0) {
String url = ps.getProperty("url");
String username = ps.getProperty("username");
String password = ps.getProperty("password");
return DriverManager.getConnection(url, username, password);
}
return null;
}
public static PreparedStatement createStatement(Connection connection, String sql, Object... params) throws Exception {
PreparedStatement ps = null;
if (connection != null) {
ps = connection.prepareStatement(sql);
if (params != null && params.length > 0) {
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
}
}
return ps;
}
public static int executeUpdate(Connection connection, String sql, Object... params) throws Exception {
int res = 0;
if (connection != null) {
PreparedStatement ps = createStatement(connection, sql, params);
if (ps != null) {
res = ps.executeUpdate();
}
}
return res;
}
public static ResultSet executQuery(Connection connection, String sql, Object... params) throws Exception {
ResultSet res = null;
if (connection != null) {
PreparedStatement ps = createStatement(connection, sql, params);
if (ps != null) {
res = ps.executeQuery();
}
}
return res;
}
public static void close(ResultSet resultset, Statement statement, Connection connection) throws Exception {
try {
if (resultset != null) resultset.close();
} finally {
try {
if (statement != null) statement.close();
} finally {
if (connection != null) connection.close();
}
}
}
}
测试:
public class Test {
public static void main(String[] args) throws Exception {
Connection conn = JdbcUtil.getConnection();
PreparedStatement ps = JdbcUtil.createStatement(conn, "select * from tbl_users");
ResultSet rs = JdbcUtil.executQuery(conn, "select * from tbl_users");
while (rs.next()) {
Long id = rs.getLong("id");
String username = rs.getString("username");
String password = rs.getString("password");
Date rdate = rs.getDate("rdate");
Boolean sex = rs.getBoolean("sex");
System.out.println(id + "\t" + username + "\t" + password + "\t" + rdate + "\t" + sex);
}
JdbcUtil.close(rs, ps, conn);
}
}