JDBC-Utils层的简单运用
项目中JDBC的Utils层运行需要以下六个步骤
//1、定义属性为空 private static String driver = null; private static String url = null; private static String username = null; private static String password = null;
//2、获取src目录下的文件并以流的形式输出---->ClassLoader类加载器 //主要是为了获取数据库的配置文件db.properties以及properties文件中早已配置好的比如JDBC连接池驱动、用户名、密码、数据库连接链接等资源 in = JDBC_Utils.class.getClassLoader().getResourceAsStream("db.properties");
// 创建Properties集合类
Properties properties = new Properties();
// 加载获取到的配置文件
properties.load(in);
// 获取资源
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
//3、加载JDBC驱动 Class.forName(driver); // forName()需要抛出ClassNotFoundException异常 }catch (IOException e){ e.printStackTrace(); }catch (ClassNotFoundException e){ e.printStackTrace(); }
//4、获取连接 public static Connection getConnection() throws SQLException { Connection conn = DriverManager.getConnection(url,username,password);
return conn;
}
//5、因为只读取一次文件,因此用的是静态代码块,执行过一次就要把资源都释放掉否则会占用系统资源。 public static void release(ResultSet rs, Connection conn, Statement stat){ // 关闭结果集 if(rs!=null){ try { rs.close(); }catch (Exception e){ e.printStackTrace(); } } // 释放连接 if(conn!=null){ try { conn.close(); }catch (Exception e){ e.printStackTrace(); } } // 释放数据库 if(stat!=null){ try { stat.close(); }catch (Exception e){ e.printStackTrace(); } } }
JDBC中Utils层的作用:使项目与数据库进行连接,相当于客户端与服务器之间建立连接的关系
连接数据库的四大参数:驱动、URL、用户名、密码
如果将来想要更改数据库,那么就要去修改这四个参数,为了修改代码的时候更快捷方便,写一个JDBC_Utils类,让它从配置文件dbconfig.properties中读取配置参数,然后创建连接对象。
附上dbconfig.properties配置文件的代码
driver = com.mysql.jdbc.Driver url = jdbc:mysql://localhost:3306/users?useUnicode=true&characterEncodeing=utf8&useSSL=true username = root password = root //说明一下url后面接的都是什么东西 //jdbc是你连接池的名字,是jdbc那就写jdbc是c3p0就写c3p0 //mysql://localhost:3306这里是数据库mysql的访问ip地址和端口号,一般都是默认为3306端口和localhost(本机ip),如果是挂载在服务器或者虚拟机上,那我就不懂咯,不过大概应该不简单 //users?这个是你的数据库名 //useUnicode=true&characterEncodeing=utf8 这里就是指定字符的编码解码格式为utf-8 //useSSL=true 是一种加密协议用来防止外界因素对数据库的随意修改,因为mysql5.7以下版本安全性比较低
以上均为个人学习记录,如有不对请大神们指正,蟹蟹~
本文来自博客园,作者:甲辰哥来帮你算命,转载请注明原文链接:https://www.cnblogs.com/linboomboom/p/14945950.html

浙公网安备 33010602011771号