从数据库工具类我们知道,连接数据库很麻烦,代码也很多,我们只需要在项目启动后像注册驱动那样执行一次这些代码即可。那么我们能不能写一个连接数据库的工具类呢?***@program:Dream*@description:数据库工具类*@author:stop.yc*@create:2022-03-1810:57**/publicclassDbUtil{私有静态字符串驱动程序=null;私有静态字符串url=null;私有静态字符串用户名=空;私人静态字符串密码=空;驱动加载只需要做一次,所以是使用静态代码块。程序运行后,运行一次*/static{try{//通过字节输入流获取文件中的配置信息。InputStreamin=DbUtil.class.getClassLoader().getResourceAsStream("db.properties");//文件加载属性properties=newProperties();属性.load(in);//获取驱动程序=properties.getProperty("驱动程序");url=properties.getProperty("url");用户名=属性。getProperty("用户名");密码=属性。getProperty("密码");//加载驱动(如果这里出现NPE,检查是否没有导入连接jar包)Class.forName(driver);}catch(Exceptione){e.printStackTrace();}}//外部调用Get连接方法,CRUD工具类调用publicstaticConnectiongetCon()throwsException{returnDriverManager.getConnection(url,username,password);}//外部调用close方法。由CRUD工具类调用publicstaticvoidclose(Connectioncon,PreparedStatementps,ResultSetrs){if(rs!=null){try{rs.close();}catch(SQLExceptione){e.printStackTrace();}}if(ps!=null){try{ps.close();}catch(SQLExceptione){e.printStackTrace();}}if(con!=null){try{con.close();}catch(SQLExceptione){e.printStackTrace();}}}}//在package同级目录下,新建文件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封装CRUDencapsulation
