大体步骤是:
1.将所有要读取的路径都写在db.properties的一个文件中,方便我们进行后续的维护
2.增删改查的sql语句写到专门的一个mapper.xml文件中,方便我们的使用
3.写一个只用来读取db.properties文件的工具类ReadPropertiesUtils
4.写一个只用来读取mapper.xml文件的工具类MapperUtils
5.导入五个jar包(等下我把jar包发到文件中)
6.写mysql的增删改的工具类MysqlCrudUtils
7.写数据库CURD的工具类JDBCUtils
8.写实体类
9.写一个增删改的测试类TestAddDeleteUpdate
------------------------------------------------------------------------------------下面是代码的呈现,按照步骤进行呈现-------------------------------------------------------------------------------------------
第一步
db.properties
mapper_url=mapper.xmldriver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/lj?characterEncoding=utf-8username=rootpassword=root
第二步
mapper.xml
<?xml version="1.0" encoding="UTF-8" ?><mapper> <select id="getStudentById"> select * from student where id = ? </select> <insert id="getStudentAdd"> insert into student (name,age,sex,phone) values(?,?,?,?) </insert> <delete id="getStudentDelete"> delete from student where id = ? </delete> <update id="getStudentUpdate"> update student set name=?,age=?,sex=?,phone=? where id = ? </update> <select id="getStudentList"> select * from student </select></mapper>
第三步
ReadPropertiesUtils
package com.cg.jdbc.utils;import java.io.IOException;import java.io.InputStream;import java.util.Properties;/*** @author: cg* @createtime: 2020/2/7 18:07* @description: 专门读取properties的工具类*/public class ReadPropertiesUtils { public static String getValueByKey(String key){ String value = null; Properties properties = new Properties(); InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"); try { properties.load(stream); value = properties.getProperty(key); } catch (IOException e) { e.printStackTrace(); } return value; }}
第四步
MapperUtils
package com.cg.jdbc.xml;import com.cg.jdbc.utils.ReadPropertiesUtils;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;import java.io.InputStream;import java.util.List;/*** @author: cg* @createtime: 2020/2/7 17:50* @description: 解析mapper.xml*/public class MapperUtils { public static final String MAPPER_URL = "mapper.xml"; /** * @author: cg * @createtime: 2020/2/7 17:51 * @description: 解析xml 获取xml中的sql */ public static String getMapperSql(String id){ //获取db.properties中的mapper路径 String mapper_url = ReadPropertiesUtils.getValueByKey("mapper_url"); String sql = ""; //读取mapper.xml文件的所在位置,转成io流 InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(mapper_url); SAXReader saxReader = new SAXReader(); try { //把获取的文件流 放入一个xml 解析对象中 Document read = saxReader.read(stream); //解析根节点 Element rootElement = read.getRootElement(); List<Element> elements = rootElement.elements(); //循环判断,是否和里面的id一致,取出来并且返回 for (Element element : elements) { //attributeValue 获取xml节点中的属性值 if(element.attributeValue("id").equals(id)){//如果两个id一致,获取id下面的sql语句 sql = element.getTextTrim(); break; } } } catch (DocumentException e) { e.printStackTrace(); } return sql; } /** * @author: cg * @createtime: 2020/2/7 18:01 * @description: 测试 */ public static void main(String[] args) { System.out.println(getMapperSql("getStudentById")); }}
第五步
MysqlCrudUtils
package com.cg.jdbc.utils;import com.cg.jdbc.entity.Student;import java.lang.reflect.Field;import java.sql.*;import java.util.ArrayList;import java.util.List;/*** @author: cg* @createtime: 2020/2/6 17:18* @description: mysql的增删改的工具类*/public class MysqlCrudUtils { /** * @author: cg * @createtime: 2020/2/6 17:18 * @description: 删除,更新,添加通用--String sql--Object[] 数组 */ public static int updateOrAddOrDelete(String sql,Object[] params) throws SQLException { //执行的结果集 int row = 0; //连接数据库 Connection connection = JDBCUtils.getConnection(); //获取preparedStatement PreparedStatement preparedStatement = JDBCUtils.getPreparedStatement(sql,connection); //轮询赋值参数 //占位符从1开始 if(null!=params && params.length>0){ int i = 1; for (Object param : params) { //先赋值后添加 preparedStatement.setObject(i++,param); } } //执行sql语句 row = preparedStatement.executeUpdate(); //关流 JDBCUtils.closeAll(null,preparedStatement,connection); return row; } /** * @author: cg * @createtime: 2020/2/6 17:29 * @description: 查询sql中的所有数据 * String sql * Object[] * Class */ public static <T>List<T> queryList(String sql,Object[] obj,Class<T> tClass) throws Exception { List<T> list = new ArrayList<>(); //连接数据库 Connection connection = JDBCUtils.getConnection(); //获取Statement的对象 //查询所有可能会条件查询,建议dao的实现类中对sql进行动态拼接,传入当前的方法 Statement statement = JDBCUtils.getStatement(connection); ResultSet resultSet = statement.executeQuery(sql); //**对于结果集进行反射的封装 Object object = null; while (resultSet.next()){ //拿到每一个对象的数据 T t = recoverToClass(tClass, resultSet); list.add(t); } //关流 JDBCUtils.closeAll(resultSet,statement,connection); return list; } /** * @author: cg * @createtime: 2020/2/6 17:37 * @description: 对数据的封装--object * 对数据的赋值 */ public static <T> T recoverToClass(Class<T> tClass,ResultSet rs) throws Exception{ //对object进行实例化,相当于A a = new A a(); T t = tClass.newInstance(); ResultSetMetaData metaData = rs.getMetaData();//拿到了数据库表的每一列 for(int i=1;i<=metaData.getColumnCount();i++){ //拿到数据库中的某一列类名 String columnLabel = metaData.getColumnLabel(i); //把数据库中的列名当成查询得key去实体中去找,如果有,则获取出来 Field field = tClass.getDeclaredField(columnLabel); //如果有的话,对实体类中的字段进行赋值 if(null!=field){ field.setAccessible(true); field.set(t,rs.getObject(i)); } } return t; } /** * @author: cg * @createtime: 2020/2/7 17:24 * @description: 查询单一的对象 返回Object */ public static <T> T queryOne(String sql,Object[] params,Class<T> tClass) throws Exception { Connection connection = JDBCUtils.getConnection(); //获取Statement的对象 //查询所有可能会条件查询,建议dao的实现类中对sql进行动态拼接,传入当前的方法 PreparedStatement preparedStatement = JDBCUtils.getPreparedStatement(sql, connection); //轮询赋值参数 if(null!=params && params.length>0){ for(int i=0;i<params.length;i++){ Object param = params[i]; preparedStatement.setObject(i+1,param); } } //执行sql语句 ResultSet resultSet = preparedStatement.executeQuery(); T t = null; if(resultSet.next()){ t = recoverToClass(tClass, resultSet); } //关闭资源 JDBCUtils.closeAll(resultSet,preparedStatement,connection); return t; } /** * @author: cg * @createtime: 2020/2/6 17:55 * @description: 简单的测试 */ public static void main(String[] args) {// String sql = "select * from student";// try {// List<Student> students = queryList(sql, null, Student.class);// for (Student student : students) {// System.out.println(student.toString());// }// } catch (Exception e) {// e.printStackTrace();// }// String sql1 = "delete from student where id = ?";// Object[] objects = {4};// try {// updateOrAddOrDelete(sql1,objects);// } catch (SQLException e) {// e.printStackTrace();// } String sql = "select * from student where id = ?"; Object[] objects = {6}; try { Student student = queryOne(sql, objects, Student.class); System.out.println(student.toString()); } catch (Exception e) { e.printStackTrace(); } }}
第六步
JDBCUtils
package com.cg.jdbc.utils;import java.io.IOException;import java.io.InputStream;import java.sql.*;import java.util.Properties;/*** @author: cg* @createtime: 2020/2/6 16:55* @description: 数据库CRUD的工具类*/public class JDBCUtils { /** * @author: cg * @createtime: 2020/2/6 16:59 * @description: 加载db.properties的文件 */ static { try { Class.forName(ReadPropertiesUtils.getValueByKey("driver")); } catch (Exception e) { e.printStackTrace(); } } /** * @author: cg * @createtime: 2020/2/6 17:06 * @description: 数据库的连接 */ public static Connection getConnection(){ Connection connection = null; try { connection = DriverManager.getConnection(ReadPropertiesUtils.getValueByKey("url"), ReadPropertiesUtils.getValueByKey("username"), ReadPropertiesUtils.getValueByKey("password")); } catch (SQLException e) { e.printStackTrace(); } return connection; } /** * @author: cg * @createtime: 2020/2/6 17:08 * @description: statement:不能防止sql注入 * preparedStatement:是以?占位符的形式替换 */ public static PreparedStatement getPreparedStatement(String sql,Connection conn){ PreparedStatement preparedStatement = null; try { preparedStatement = conn.prepareStatement(sql); } catch (SQLException e) { e.printStackTrace(); } return preparedStatement; } /** * @author: cg * @createtime: 2020/2/6 17:12 * @description: */ public static Statement getStatement(Connection conn){ Statement statement = null; try { statement = conn.createStatement(); } catch (SQLException e) { e.printStackTrace(); } return statement; } /** * @author: cg * @createtime: 2020/2/6 17:14 * @description: 关闭资源 */ public static void closeAll(ResultSet rs,Statement statement,Connection conn){ try { if(null!=rs){ rs.close(); } if(null!=statement){ statement.close(); } if(null!=conn){ conn.close(); } } catch (SQLException e) { e.printStackTrace(); } }}
第七步
实体类
package com.cg.jdbc.entity;public class Student { private int id; private String name; private int age; private String sex; private String phone; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + ", phone='" + phone + '\'' + '}'; }}
第八步
测试增删改TestAddDeleteUpdate
package com.cg.jdbc.test;import com.cg.jdbc.entity.Student;import com.cg.jdbc.utils.MysqlCrudUtils;import com.cg.jdbc.xml.MapperUtils;import org.junit.Test;import javax.sound.midi.Soundbank;import java.sql.SQLException;import java.util.List;/*** @author: cg* @createtime: 2020/2/7 18:37* @description: junit测试增删改的操作*/public class TestAddDeleteUpdate { /** * @author: cg * @createtime: 2020/2/7 20:06 * @description: 添加 */ @Test public void add() throws SQLException { Object[] objects = {"添加",22,"女","12511211322"}; int addi = MysqlCrudUtils.updateOrAddOrDelete(MapperUtils.getMapperSql("getStudentAdd"), objects); if(addi>0){ System.out.println("添加成功"); }else { System.out.println("添加失败"); } } /** * @author: cg * @createtime: 2020/2/7 20:08 * @description: 查询所有 */ @Test public void list() throws Exception{ List<Student> list = MysqlCrudUtils.queryList(MapperUtils.getMapperSql("getStudentList"), null, Student.class); for (Student student : list) { System.out.println(student.toString()); } } /** * @author: cg * @createtime: 2020/2/7 20:12 * @description: 删除 */ @Test public void delete() throws Exception{ Object[] objects = {6}; int deleteI = MysqlCrudUtils.updateOrAddOrDelete(MapperUtils.getMapperSql("getStudentDelete"), objects); if(deleteI>0){ System.out.println("删除成功"); }else { System.out.println("删除失败"); } } /** * @author: cg * @createtime: 2020/2/7 20:16 * @description: 修改 */ @Test public void update() throws Exception{ Object[] objects = {"update",56,"男","88866644455",7}; int upi = MysqlCrudUtils.updateOrAddOrDelete(MapperUtils.getMapperSql("getStudentUpdate"), objects); if(upi>0){ System.out.println("修改成功"); }else{ System.out.println("修改失败"); } } /** * @author: cg * @createtime: 2020/2/7 20:27 * @description: 单个查询 */ @Test public void listOne() throws Exception{ Object[] objects = {8}; Student getStudentById = MysqlCrudUtils.queryOne(MapperUtils.getMapperSql("getStudentById"), objects, Student.class); System.out.println(getStudentById.toString()); }}
来源:https://www.cnblogs.com/chen-gang/p/12285540.html