1 将哪些操作抽取到工具类中
为什么要抽取工具类?
我们在执行CRUD的过程中,有太多的重复代码需要写,例如:注册驱动、获取连接、释放资源【可以优化dao层的代码】
1 加载properties配置文件,获取连接数据库的相关参数,4个
加载一次,写到static静态代码块中
2 注册驱动
加载一次,写到static静态代码块中
3 提供一个静态方法,获取连接
4 提供一个静态方法,释放资源
2 在src中书写jdbc.properties配置文件
注:jdbc.properties配置文件不要写到包中了
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8&usesSL=true
userName=root
passWord=123456
3 书写JDBCUtils工具类
public class JdbcUtils {private static String url;private static String userName;private static String passWord;/*在JdbcUtils工具类中需要做哪些事?*1加载jdbc.properties文件,读取属性文件中的内容(只需加载一次)--静态代码块* 2注册驱动(只需加载一次)--静态代码块*///只加载一次static {//1加载jdbc.properties文件,读取属性文件中的内容(只需要加载一次)//1.1创建Properties对象try {Properties properties = new Properties();//1.2调用Load方法加载属性文件//反射中是获取Class对象,那么也就意味着Class对象我们不能new,//那么是哪里来的Class对象,也就是说谁帮我们创建了Class对象呢?InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");properties.load(is);//1.3从properties对象中根据key获取value值String driverClassName = properties.getProperty("driverClassName");url = properties.getProperty("url");userName = properties.getProperty("userName");passWord = properties.getProperty("passWord");//2.注册驱动Class.forName(driverClassName);} catch (Exception e) {e.printStackTrace();}}/** 3.获取连接(对外提供方法,可多次使用)* 4.释放资源(对外提供方法,可多次使用)* *///写成方法,可多次调用//获取连接public static Connection getConnection(){Connection conn = null;try {conn = DriverManager.getConnection(url, userName, passWord);} catch (SQLException e) {e.printStackTrace();}return conn;}//释放资源【参数没有则传入null】public static void close(Connection conn, Statement stat,ResultSet rs){try {if (rs != null) {rs.close();}} catch (SQLException e) {e.printStackTrace();}try {if (rs != null) {stat.close();}} catch (SQLException e) {e.printStackTrace();}try {if (rs != null) {conn.close();}} catch (SQLException e) {e.printStackTrace();}}
}
注:释放资源方法【参数没有则传入null】