JDBC--DAOUtil封装
目录
一、DAOUtil封装
1.1增删改查
1.1 .1增
1.1.2删
1.1.3 改
1.1.4 查询一个
1.1.5 查询全部
二 、DAOUtil的封装
2.1连接函数的封装 1分钟
2.2 加载驱动 1分钟
2.3 魔法值优化 1 分钟
2.4 DML通用函数 4分钟
2.5 可变参数优化数组传参
完整版
一、DAOUtil封装
1.1增删改查
1.1 .1增
@Testpublic void add() throws Exception {People people = new People(0, "haha", 18, "男", "QY134");String sql = "insert into t_student values (null,?,?,?,?)";Class.forName( "com.mysql.jdbc.Driver" );Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?characterEncoding=UTF-8&useSSL=false", "root", "123456");PreparedStatement ps = conn.prepareStatement(sql);ps.setObject( 1 , people.getName() );ps.setObject( 2 , people.getAge() );ps.setObject( 3 , people.getSex() );ps.setObject( 4 , people.getGrade() );int i = ps.executeUpdate();ps.close();conn.close();}
1.1.2删
@Testpublic void delete() throws Exception{String sql = "delete from t_student where id = ?";Class.forName( "com.mysql.jdbc.Driver" );Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?characterEncoding=UTF-8&useSSL=false", "root", "123456");PreparedStatement ps = conn.prepareStatement(sql);ps.setObject(1,51);int i = ps.executeUpdate();ps.close();conn.close();}
1.1.3 改
@Testpublic void update() throws Exception{People people = new People(55, "阿木", 18, "女", "123");String sql = "update t_student set name=?,age=?,sex=?,grade=? where id = ?";Class.forName( "com.mysql.jdbc.Driver" );Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ry?characterEncoding=UTF-8&useSSL=false", "root", "123456");PreparedStatement ps = conn.prepareStatement(sql);ps.setObject(1 , people.getName());ps.setObject(2 , people.getAge());ps.setObject(3 , people.getSex());ps.setObject(4 , people.getGrade());ps.setObject(5 , people.getId());int i = ps.executeUpdate();ps.close();conn.close();}
1.1.4 查询一个
@Testpublic void selectOne() throws Exception{String sql = "select * from 表名 where id = ?";Class.forName( "com.mysql.jdbc.Driver" );Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?characterEncoding=UTF-8&useSSL=false", "root", "123456");PreparedStatement ps = conn.prepareStatement(sql);ps.setObject(1,55);ResultSet resultSet = ps.executeQuery();int columnCount = resultSet.getMetaData().getColumnCount();List<Map<String,Object>> list = new ArrayList<>();while (resultSet.next()){Map<String, Object> map = new HashMap<>();for (int i =1 ; i<=columnCount;i++){map.put(resultSet.getMetaData().getColumnLabel(i) , resultSet.getObject(i) );}list.add(map);}resultSet.close();ps.close();conn.close();// [ {sex=男, grade=123, name=asd, id=55, age=18} ]System.out.println( list .get( 0 ) .get("sex") );}
1.1.5 查询全部
@Testpublic void selectAll() throws Exception{String sql = "select * from 表名";Class.forName( "com.mysql.jdbc.Driver" );Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?characterEncoding=UTF-8&useSSL=false", "root", "123456");PreparedStatement ps = conn.prepareStatement(sql);ResultSet resultSet = ps.executeQuery();int columnCount = resultSet.getMetaData().getColumnCount();List<Map<String,Object>> list = new ArrayList<>();while (resultSet.next()){Map<String, Object> map = new HashMap<>();for (int i =1 ; i<=columnCount;i++){map.put(resultSet.getMetaData().getColumnLabel(i) , resultSet.getObject(i) );}list.add(map);}resultSet.close();ps.close();conn.close();System.out.println(list);}
二 、DAOUtil的封装
2.1连接函数的封装 1分钟
Class.forName( "com.mysql.jdbc.Driver" );Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?characterEncoding=UTF-8&useSSL=false", "root", "123456");这两句代码重复了 并且每次都需要使用 所以我们可以将其封装成一个函数 需要使用的时候 直接调用即可A 创建一个工具类
public class DAOUtil {}B 将连接函数封装到 工具类中public static Connection getConnection() throws Exception{Class.forName( "com.mysql.jdbc.Driver" );Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?characterEncoding=UTF-8&useSSL=false", "root", "123456");return conn;}
C 在原有类 通过调用的形式 拿到连接对象@Testpublic void selectAll() throws Exception{String sql = "select * from 表名";Connection conn = DAOUtil.getConnection();PreparedStatement ps = conn.prepareStatement(sql);
2.2 加载驱动 1分钟
现在我们将 加载驱动的代码 Class.forName( "com.mysql.jdbc.Driver" ); 写到 getConnection 封装函数中,
当我们进行增删改操作的时候,只要调用 getConnection 就会加载一次驱动。 我们每次增删改查 获取连接对象是没有问题的,但是每次都去加载驱动 显然浪费。就好像 我们 每次开机 都需要安装一次网卡驱动,没必要。所以我们需要将 加载驱动的代码 写到一个只执行一次的位置。public class DAOUtil {static {try {Class.forName( "com.mysql.jdbc.Driver" );} catch (ClassNotFoundException e) {e.printStackTrace();}}public static Connection getConnection() throws Exception{return DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?characterEncoding=UTF-8&useSSL=false", "root", "123456");}}
2.3 魔法值优化 1 分钟
public class DAOUtil {private static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";private static final String URL = "jdbc:mysql://localhost:3306/数据库名?characterEncoding=UTF-8&useSSL=false";private static final String USERNAME = "root";private static final String PASSWORD = "123456";static {try {Class.forName( DRIVER_CLASS );} catch (ClassNotFoundException e) {e.printStackTrace();}}public static Connection getConnection() throws Exception{return DriverManager.getConnection(URL, USERNAME, PASSWORD);}}
2.4 DML通用函数 4分钟
小优化:@Testpublic void add() throws Exception {People people = new People(0, "haha", 18, "男", "123");String sql = "insert into 表名 values (null,?,?,?,?)";Object[] data = { people.getName() , people.getAge() , people.getSex() , people.getGrade() };Connection conn = DAOUtil.getConnection();PreparedStatement ps = conn.prepareStatement(sql);ps.setObject( 1 , data[0] );ps.setObject( 2 , data[1] );ps.setObject( 3 , data[2] );ps.setObject( 4 , data[3] );int i = ps.executeUpdate();ps.close();conn.close();} @Testpublic void update() throws Exception{People people = new People(55, "阿木", 18, "女", "123");String sql = "update t_student set name=?,age=?,sex=?,grade=? where id = ?";Object[] data = { people.getName() , people.getAge() , people.getSex() , people.getGrade() ,people.getId() };Connection conn = DAOUtil.getConnection();PreparedStatement ps = conn.prepareStatement(sql);for (int i=0;i<data.length;i++){ps.setObject( i+1 , data[i] );}int i = ps.executeUpdate();ps.close();conn.close();}
此时我们发现 增删改 太重复了 ,我们将重复代码 进行封装public static int executeUpdate(String sql,Object[] data) {Connection conn = null;try {conn = DAOUtil.getConnection();PreparedStatement ps = conn.prepareStatement(sql);for (int i=0;i<data.length;i++){ps.setObject( i+1 , data[i] );}int i = ps.executeUpdate();return i;} catch (Exception e) {e.printStackTrace();} finally {try {if(conn != null) conn.close();} catch (SQLException e) {e.printStackTrace();}}return 0;}@Testpublic void add() throws Exception {People people = new People(0, "haha", 18, "男", "123");String sql = "insert into t_student values (null,?,?,?,?)";Object[] data = { people.getName() , people.getAge() , people.getSex() , people.getGrade() };int i = DAOUtil.executeUpdate(sql, data);System.out.println(i);}
2.5 可变参数优化数组传参
public static int executeUpdate(String sql,Object... data) {Connection conn = null;try {conn = DAOUtil.getConnection();PreparedStatement ps = conn.prepareStatement(sql);for (int i=0;i<data.length;i++){ps.setObject( i+1 , data[i] );}int i = ps.executeUpdate();return i;} catch (Exception e) {e.printStackTrace();} finally {try {if(conn != null) conn.close();} catch (SQLException e) {e.printStackTrace();}}return 0;}@Testpublic void add() throws Exception {People people = new People(0, "haha", 18, "男", "123");String sql = "insert into t_student values (null,?,?,?,?)";int i = DAOUtil.executeUpdate(sql, people.getName() , people.getAge() , people.getSex() , people.getGrade());System.out.println(i);}@Testpublic void delete() throws Exception{String sql = "delete from t_student where id = ?";Object[] data = {51};int i = DAOUtil.executeUpdate(sql, 51);System.out.println(i);}@Testpublic void update() throws Exception{People people = new People(55, "阿木", 18, "女", "123");String sql = "update t_student set name=?,age=?,sex=?,grade=? where id = ?";int i = DAOUtil.executeUpdate(sql, people.getName() , people.getAge() , people.getSex() , people.getGrade() ,people.getId());System.out.println(i);}底层原理@Testpublic void add() throws Exception {People people = new People(0, "haha", 18, "男", "123");String sql = "insert into t_student values (null,?,?,?,?)";int i = DAOUtil.executeUpdate(sql, new Object[]{people.getName(), people.getAge(), people.getSex(), people.getGrade()});System.out.println(i);}@Testpublic void delete() throws Exception {String sql = "delete from t_student where id = ?";Object[] var10000 = new Object[]{51};int i = DAOUtil.executeUpdate(sql, new Object[]{51});System.out.println(i);}@Testpublic void update() throws Exception {People people = new People(55, "阿木", 12, "女", "123");String sql = "update t_student set name=?,age=?,sex=?,grade=? where id = ?";int i = DAOUtil.executeUpdate(sql, new Object[]{people.getName(), people.getAge(), people.getSex(), people.getGrade(), people.getId()});System.out.println(i);}
@Test
public void add(){People people = new People(0, "hahahaha", 19, "男", "123");String sql = "insert into t_student values (null,?,?,?,?)";int i = DAOUtil.executeUpdate(sql, people.getName(), people.getAge(), people.getSex(), people.getGrade());System.out.println(i);}@Test
public void delete(){String sql = "delete from t_student where id = ?";int i = DAOUtil.executeUpdate(sql, 66);System.out.println(i);}@Test
public void update(){People people = new People(76, "zhangsan", 23, "女", "789");String sql = "update t_student set name=? where id = ?";int i = DAOUtil.executeUpdate(sql, people.getName(), people.getId());System.out.println(i);}
完整版
package com.am.test;import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;public class DAOUtil {private static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";private static final String URL = "jdbc:mysql://localhost:3306/数据库名?characterEncoding=UTF-8&useSSL=false";private static final String USERNAME = "root";private static final String PASSWORD = "123456";static {try {Class.forName( DRIVER_CLASS );} catch (ClassNotFoundException e) {e.printStackTrace();}}public static Connection getConnection() throws Exception{return DriverManager.getConnection(URL, USERNAME, PASSWORD);}public static int executeUpdate(String sql,Object... data) {Connection conn = null;try {conn = DAOUtil.getConnection();PreparedStatement ps = conn.prepareStatement(sql);for (int i=0;i<data.length;i++){ps.setObject( i+1 , data[i] );}int i = ps.executeUpdate();return i;} catch (Exception e) {e.printStackTrace();} finally {try {if(conn != null) conn.close();} catch (SQLException e) {e.printStackTrace();}}return 0;}}
喜欢学习编写的小伙伴有福音了,木仔会每天发布一些学习资料以及笔记,想看更多学习资料点击此处A_M阿木的博客_CSDN博客-领域博主
JDBC--DAOUtil封装相关推荐
- JDBC之封装通用的BaseDao
JDBC之封装通用的BaseDao 以上篇文章(JDBC之在分层结构中实现业务)为基础,进行封装更新操作: 一.持久层(数据访问层) 在dao包下创建通用方法接口BaseDao public inte ...
- java中jdbc的封装笔记_JDBC封装学习笔记(三)---面向对象的JDBC,使用preparedStatement...
使用PreparedStatement对象:为什么要使用PreparedStatement 原因:(1)使用Statement需要拼接SQL,太费劲,也容易出错. String sql = " ...
- JDBC、封装JDBC连接池、第三方连接池工具
主要内容: JDBC简介 JDBC来源 通过代码实现JDBC JDBC的改进需求 JDBC改进的代码实现 JDBC使用的设计模式 封装连接池 封装JDBC连接池 ThreadLoacl的使用 Thre ...
- DBUtils开源JDBC类库,对JDBC简单封装(作用是:简化编码工作量,同时不会影响程序的性能)...
DBUtils:提高了程序的性能,编程更加简便 架包 mysql-connector-java-jar commons-dbcp-1.4jar commons-pool-1.5.5jar common ...
- 零基础入门JAVAweb——JDBC的封装篇
- jdbc封装与多并发的共鸣
欢迎来到:http://observer.blog.51cto.com 代码的封装是一门艺术,封装得好,不但给自己便利,还可以给自己的维护提供帮助:同时,封装得好,还可以给看自己代码的人以赏心悦目的感 ...
- 【JDBC】实现对JDBC 连接的简单封装
package util;import java.sql.Connection; import java.sql.DriverManager;/**** 实现对JDBC 的封装* @author mq ...
- 高性能jdbc封装工具 Apache Commons DbUtils 1.6(转载)
转载自原文地址:http://gao-xianglong.iteye.com/blog/2166444 前言 关于Apache的DbUtils中间件或许了解的人并不多,大部分开发人员在生成环境中更多的 ...
- java jdbc封装_JDBC封装-Java(新手)
JDBC的封装,自己总结的自己总结的自己总结的 dao (代码分层)命名规范: 1.com.XXX.dao 存放dao相关的类型 例如 StudentDAOImpl 处理 数据库的链接 存取数据 2. ...
- Java学习——JDBC之从导Jar包到封装
书籍就像一盏神灯,它照亮人们最遥远.最黯淡的生活道路.--乌皮特 前言:下面内容是本人Java初学者的学习内容 前提准备:已经安装好mysql数据库,若没有请看Mysql8.0的下载安装 需要学习SQ ...
最新文章
- 【Codeforces】716B Complete the Word (26个字母)
- Sean Lynch谈Facebook Claspin监控工具的由来
- boost::histogram::indexed用法的测试程序
- C++使用Merge Sort排序计数反转的实现算法(附完整源码)
- JDK 11:Java序列化的终结开始了吗?
- Maven简述以及配置使用
- NHibernate:no persister for 异常
- 机器学习焦点,范德比尔特(Vanderbilt U)的医疗机器人以及更多开源新闻
- Josephus 线段数版
- java 成员初始化_静态成员及其初始化
- 【Office 365 2108更新】
- LeetCode刷题复盘笔记—一文搞懂509. 斐波那契数70. 爬楼梯以及递归时间复杂度计算方法(动态规划系列第一篇)
- tableau数据汇总/明细/分-总的行列展示— Lee桑的学习笔记
- Python 定时获取卫星图像做为桌面背景
- 第二章 SQL命令参考-REASSIGN OWNED
- python pptx 关于在ppt里插入表格,调整合并单元格的问题
- Windows 2003安全设置大全----2003系统错误大全解释
- 【ZYNQ】 cache解决问题
- je学习笔记一:jsp页面
- css技术点二:字体图标(阿里巴巴字体图标使用)
热门文章
- 华硕笔记本进bios按哪个键 华硕手提电脑怎么进bios设置
- python制作日历并保存成excel_[python]获取一年日历数据并写入excel表格中
- qlv格式转Mp4格式
- 68个经典励志小故事|哲理小故事,让你终身受益(1)
- 多径信道误码率理论仿真
- 找不到文件“c:/Users/Administrator/Desktop/vue_dom2/node_modules/postcss-discard-overridden/types/index.d.
- 海康摄像头拍照(java版,拿走即用)
- pytorch实用工具总结(GFLOPs如何计算)
- 记一次磁盘PV丢失事件
- 如果要做 Rietveld 分析,XRD时步长需要满足什么要求