安康网站开发公司,wordpress建站主题,wordpress是公益,wordpress 页面1 将哪些操作抽取到工具类中
为什么要抽取工具类#xff1f; 我们在执行CRUD的过程中#xff0c;有太多的重复代码需要写#xff0c;例如#xff1a;注册驱动、获取连接、释放资源【可以优化dao层的代码】 1 加载properties配置文件#xff0c;获取连接数据库的相关参数 我们在执行CRUD的过程中有太多的重复代码需要写例如注册驱动、获取连接、释放资源【可以优化dao层的代码】 1 加载properties配置文件获取连接数据库的相关参数4个 加载一次写到static静态代码块中 2 注册驱动 加载一次写到static静态代码块中
3 提供一个静态方法获取连接 4 提供一个静态方法释放资源
2 在src中书写jdbc.properties配置文件
注jdbc.properties配置文件不要写到包中了
driverClassNamecom.mysql.jdbc.Driver
urljdbc:mysql://localhost:3306/jdbc?useUnicodetruecharacterEncodingutf8usesSLtrue
userNameroot
passWord1234563 书写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】