JDBC工具类
JDBC工具类
通过封装相关操作,创建JDBC相关的方法,如创建连接、关闭资源等,提升代码的可重用性。
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class JDBCUtil {
private static final String DRIVER_NAME="com.mysql.cj.jdbc.Driver";
private static String url="";
private static String user="";
private static String psw="";
static {
try {
Class.forName(DRIVER_NAME);
Properties properties = new Properties();
try {
//FileInputStream fileInputStream = new FileInputStream("day24/src/db.properties");
//properties.load(fileInputStream);
properties.load(JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties"));
user = properties.getProperty("user");
psw = properties.getProperty("psw");
url = properties.getProperty("url");
} catch (IOException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
}
public static Connection getConnection(){
Connection connection = null;
try {
connection = DriverManager.getConnection(url,user,psw);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return connection;
}
public static void close(Connection connection){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static void close(Statement statement){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static void close(ResultSet resultSet){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}