java中对sql进行操作时产生了大量重复的代码,于是可以将这些重复的代码添加到一个工具类中去,简化代码的书写过程。
1.注册驱动
2.抽取一个方法获取连接对象 需求,不传递参数,静态代码块,配置文件
jdbc.properties
url=
user=
password=
util代码
static String url;
static String user;
static String password;
static String driver;
/*静态代码块*/
static {
try {
Properties pro = new Properties();
//获取src路径下文件的方法 Classloader
ClassLoader classLoader = JDBCuUtils.class.getClassLoader();
URL res =classLoader.getResource("jdbc.properties");
String path = res.getPath();
pro.load(new FileReader(path));
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
/*执行增删改查语句时要关闭stmt和conn两个对象*/
public static void close(Statement stmt, Connection conn) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/*执行查询语句时要关闭stmt,conn和rs三个对象,按照从小到大关闭资源*/
public static void close(Statement stmt, Connection conn, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}