数据库工具类
通过学习咱们晓得,连贯一个数据库很麻烦,代码很多,而且像注册驱动这些代码咱们在我的项目的启动后只须要执行一次。所以咱们能不能写一个数据库连贯的工具类嘞?
** * @program: Dream * @description: 数据库工具类 * @author: stop.yc * @create: 2022-03-18 10:57 **/public class DbUtil { private static String driver = null; private static String url = null; private static String username = null; private static String password = null; /*配置信息,程序运行后,只有一次,就不会扭转了,而后驱动加载也只须要一次,那么就是用动态代码块,程序运行后,运行一次*/ static { try { //通过字节输出流,获取文件中的配置信息. InputStream in = DbUtil.class.getClassLoader().getResourceAsStream("db.properties"); //文件加载 Properties properties = new Properties(); properties.load(in); //获取 driver = properties.getProperty("driver"); url = properties.getProperty("url"); username = properties.getProperty("username"); password = properties.getProperty("password"); //加载驱动(如果在这里呈现NPE的话,看看是不是没有导入连贯jar包) Class.forName(driver); } catch (Exception e) { e.printStackTrace(); } } //内部调用获取连贯办法,被CRUD工具类调用 public static Connection getCon() throws Exception { return DriverManager.getConnection(url,username,password); } //内部调用敞开办法.被CRUD工具类调用 public static void close(Connection con,PreparedStatement ps,ResultSet rs) { if(rs!=null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps!=null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(con!=null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } }}//包同级目录下,新建一个文件,db.properties,内容如下:driver=com.mysql.jdbc.Driver#db——dream为你的项目名称url=jdbc:mysql://localhost:3306/db_dream?useUnicode=true&characterEncoding=utf8&useSSL=false#数据库的账号密码username=usernamepassword=password
对于CRUD工具类,就请到另一篇文章看看,顺便学习一下CRUD的封装