数据库工具类
2022/5/5 2:12:52
本文主要是介绍数据库工具类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
数据库工具类
通过学习我们知道,连接一个数据库很麻烦,代码很多,而且像注册驱动这些代码我们在项目的启动后只需要执行一次。所以我们能不能写一个数据库连接的工具类呢?
** * @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=username password=password
关于CRUD工具类,就请到另一篇文章看看,顺便学习一下CRUD的封装 CRUD
这篇关于数据库工具类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?
- 2024-05-09企业src漏洞挖掘-有意思的命令执行