JDBC工具类
2022/8/2 23:24:07
本文主要是介绍JDBC工具类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
JDBC工具类
目的:简化代码书写
分析:
1,注册驱动也抽取
2,抽取一个方法获取连接对象
3,抽取一个方法释放资源
在我们使用JDBC 的时候,我们多数的代码都是一样的,这个时候我们就像能不能把相同的代码包装成静态方法给我们使用,这就是我们所谓的JDBC工具类
public class JDBCUtils { private static String url ; private static String user ; private static String password ; private static String driver; static { Properties pro = new Properties(); //这里是通过类加载器获取jdbc.propertise的绝对路径 //首先获取类的加载器,然后通过类的加载器获取src路径下资源的绝对路径 //这里的意思是不管模块如何移植,只要在模块当中,就能通过相对路径找到 //绝对路径 ClassLoader loader = JDBCUtils.class.getClassLoader(); //通过类加载器获取scr路径下的资源的绝对路径 URL res = loader.getResource("JDBC.properties"); //获取绝对路径 String path = res.getPath(); try { pro.load(new FileReader(path)); } catch (IOException e) { e.printStackTrace(); } url = pro.getProperty("url"); user = pro.getProperty("user"); password = pro.getProperty("password"); driver = pro.getProperty("driver"); try { Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url,user,password); } public static void close(Statement stmt, Connection conn){ if (stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(ResultSet rs,Statement stmt, Connection conn){ if (rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
这篇关于JDBC工具类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升