代码:
public class JDBCUtils {
private static Connection connection = null;
public static Connection getConnection() throws Exception {
InputStream resourceAsStream = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbcConnection.properties");
Properties info = new Properties();
info.load(resourceAsStream);
String username = info.getProperty("username");
String password = info.getProperty("password");
String driver = info.getProperty("driver");
String url = info.getProperty("url");
Class.forName(driver);
connection = DriverManager.getConnection(url, username, password);
return connection;
}
public static void closeResource(Connection connection, Statement preparedStatement) {
try {
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (SQLException throwable) {
throwable.printStackTrace();
}
try {
if (connection != null) {
connection.close();
}
} catch (SQLException throwable) {
throwable.printStackTrace();
}
}
public static void update(String sql, Object... args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}
preparedStatement.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.closeResource(connection, preparedStatement);
}
}
}
public <T> List<T> getForList(Class<T> clazz, String sql, Object... args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSetMetaData metaData = null;
ResultSet resultSet = null;
ArrayList<T> arrayList = new ArrayList<>();
try {
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}
resultSet = preparedStatement.executeQuery();
metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
while (resultSet.next()) {
T t = clazz.getDeclaredConstructor().newInstance();
for (int i = 0; i < columnCount; i++) {
Object value = resultSet.getObject(i + 1);
String columnLabel = metaData.getColumnLabel(i + 1);
Field declaredField = t.getClass().getDeclaredField(columnLabel);
declaredField.setAccessible(true);
declaredField.set(t, value);
}
arrayList.add(t);
}
return arrayList;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
IDEA中直接使用properties文件的方法:
- 在模块中新建一个目录,命名为resource
- 右键单击这个目录,在最下方找标记目录为,然后点标记为测试资源
- 在目录中放置properties文件即可。
Properties中的信息(注意等号前后一定不要有空格),以及注意事项
username=root
password=123456789
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc_learn?serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true
注意事项