
4.JDBC与代码重构
发布日期:2021-05-06 18:58:17
浏览次数:27
分类:精选文章
本文共 2332 字,大约阅读时间需要 7 分钟。
对于之前的处理数据库的方法有大量代码是相同的,如注册驱动,建立连接,关闭连接
因此可以将相同代码专门封装在JDBCUtil类中 之后建立连接可以调用JDBCUtil.getConn()方法 关闭文件可以调用JDBCUtil.closeConn()方法package cn.edu.hbue.wmp;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class JDBCUtil { static{ try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("JDBC driver error"); e.printStackTrace(); } } public static Connection getConn() { Connection connection = null; try { String url = "jdbc:mysql://localhost:3306/grade" + "?user=root&password=18170021&serverTimezone=UTC"; connection = DriverManager.getConnection(url); }catch (SQLException e) { System.out.println("JDBC connection error"); e.printStackTrace(); } return connection; } public static void closeConn(Statement stmt,Connection conn) { try{ if(stmt!= null) stmt.close(); if(conn!=null) conn.close(); }catch(SQLException e){ System.out.println("close error"); e.printStackTrace(); } } //之后查询要用到ResultSet public static void closeConn(ResultSet rs, Statement stmt, Connection conn){ try{ if(rs != null){ rs.close(); } if(stmt!= null) stmt.close(); if(conn!=null) conn.close(); }catch(SQLException e){ System.out.println("close error"); e.printStackTrace(); } }}
例:通用删除
package cn.edu.hbue.wmp;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;public class GeneralJDBCUpdate { public static void main(String[] args) { // TODO Auto-generated method stub String sql = "delete from student where id = ?"; //有个id占位符,之后要填充,也就是通过id确定删除 update(sql,11); } //要传入sql语句和不确定的占位符 public static void update(String sql,Object ... args){ Connection connection = null; PreparedStatement ps = null; //1.获取连接 connection = JDBCUtil.getConn(); try { //2.预编译sql语句 ps = connection.prepareStatement(sql); //3.填充占位符 for(int i = 0;i < args.length;i++){ ps.setObject(i + 1, args[i]); } //4.执行sql语句 ps.execute(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ //5.关闭资源 JDBCUtil.closeConn(ps,connection); } }}
发表评论
最新留言
感谢大佬
[***.8.128.20]2025年03月27日 13时08分52秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
SQL 查询强化 - 数据准备
2019-03-06
SQL 强化练习 (四)
2019-03-06
SQL 强化练习 (八)
2019-03-06
Excel 拼接为 SQL 并打包 exe
2019-03-06
Pandas数据分析从放弃到入门
2019-03-06
Matplotlib绘制漫威英雄战力图,带你飞起来!
2019-03-06
机器学习是什么
2019-03-06
《小王子》里一些后知后觉的道理
2019-03-06
《自私的基因》总结
2019-03-06
《山海经》总结
2019-03-06
《非暴力沟通》总结
2019-03-06
《你当像鸟飞往你的山》总结
2019-03-06
《我是猫》总结
2019-03-06
《抗糖化书》总结
2019-03-06
apache虚拟主机配置
2019-03-06
光盘作为yum源
2019-03-06
PHP 正则表达式资料
2019-03-06
PHP官方网站及PHP手册
2019-03-06
mcrypt加密以及解密过程
2019-03-06
mysql连续聚合
2019-03-06