使用JDBC实现对数据的增删改查(源码注释)

数据库查询结果:

对于数据库的增删改查是我们使用数据库的基础,我们需要熟练掌握,在这里写了对数据库的增删改查操作,实现对于数据库的基本操作。增删改 //属于同一类方法调用,查由于需要返回查询的结果,需要重新修改一下方法。

 

前提条件:安装mysql数据库,项目内导入mysql对应版本的驱动包;

项目中的结构:

jdbc.properties  存储了数据库的连接信息 ,内容如下(修改自己对应的用户名,密码 以及连接的数据库名称):

JDBCUtils.java

作为管理数据库的工具类,减少重复的操作,主要是获取连接的方法,和关闭资源的方法。

//package com.bhlc.util;

/**
 * @author 
 * @date 2019
 */

import com.bhlc.jdbc.ConnectionTest;
import com.mysql.cj.x.protobuf.MysqlxPrepare;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 *  操作数据库的实现类
 *
 */
public class JDBCUtils {
    /**
     * 获取数据库的连接
     * @return
     * @throws Exception
     */
    public static Connection getConnection() throws  Exception{
        //读取配置文件中的信息
        InputStream is= ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
        Properties pros=new Properties();
        pros.load(is);
        String user=pros.getProperty("user");
        String password=pros.getProperty("password");
        String url=pros.getProperty("url");
        String driverClass=pros.getProperty("driverClass");

        //2.加载驱动
        Class.forName(driverClass);
        //3.获取链接
        Connection conn= DriverManager.getConnection(url,user,password);
        return  conn;

    }

    /**
     * 关闭连接和statement操作
     * @param conn
     * @param ps
     */
    public static void closeResource(Connection conn, Statement ps ){
        //7.资源的关闭
        try {
            if(ps!=null)
            ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(conn!=null)
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     *  关闭资源的操作  查操作
     * @param conn
     * @param ps
     * @param rs
     */
    public static void closeResource(Connection conn, Statement ps,ResultSet rs  ){
        try {
            if(ps!=null)
                ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(conn!=null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if(rs!=null)
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Student.java 

用来封装student表中的属性以及重写toString方法

//package com.bhlc.preparedstatement;

/**
 * @author 
 * @date 2019
 */

/**
 *
 * ORM编程思想(object relational mapping)
 * 一个数据表对应一个jave类
 * 表中的一条数据对应java类的一个对象
 * 表中的一个字段对应java类中共的一个属性
 */

public class Student {
    public Student(){
 super();
    }
    private int id;

    public Student(int id, String studentno, Double score) {
        super();
        this.id=id;
        this.studentno=studentno;
        this.score=score;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getStudentno() {
        return studentno;
    }

    public void setStudentno(String studentno) {
        this.studentno = studentno;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    private String studentno;
    private double score;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", studentno='" + studentno + '\'' +
                ", score=" + score +
                '}';
    }
}

PreparedStatementUpdateTest.java

这里,没有使用main 方法,关于增删改的操作都是直接用测试方法 进行测试的。(注释很详细,用了不同的方法)

//package com.bhlc.preparedstatement;

/**
 * @author 
 * @date 
 */


import com.bhlc.jdbc.ConnectionTest;
import com.bhlc.util.JDBCUtils;
import com.mysql.cj.x.protobuf.MysqlxCrud;
import com.sun.org.apache.xml.internal.resolver.readers.ExtendedXMLCatalogReader;
import org.junit.Test;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

/**
 * 使用PreparedStatement 代替Statement,实现对数据表的增删改查操作
 *  增删改,查
 */
public class PreparedStatementUpdateTest {
    @Test
    public void testCommonUpdate(){
        String sql="delete from result where id=?";
        update(sql,4);
    }

    //创建一个通用的增删改操作
    public void update(String sql,Object ...args) { //sql中占位符的位数与可变形参的个数相等
        Connection conn= null;
        PreparedStatement ps= null;
        try {
            //1.获取数据库的连接
            conn = JDBCUtils.getConnection();
            //2.预编译sql语句返回prepareStatementc的实例
            ps = conn.prepareStatement(sql);
            //3.填充占位符
            for(int i=0;i<args.length;i++) {
                ps.setObject(i + 1, args[i]);  //小心参数声明错误
            }   //4.执行
                ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

            //5.关闭资源
            JDBCUtils.closeResource(conn,ps);

        }

        }
    //修改customer表的一条记录
    @Test
    public void testUpdate() throws Exception{
        //1.获取数据库的连接
        Connection conn  = JDBCUtils.getConnection();


        //2.预编译sql语句,返回PreparedStatement的实例
        String sql="update result set studentno=?where id=?";

        PreparedStatement ps  = conn.prepareStatement(sql);

        //3.填充占位符
         ps.setObject(1,"liuliuliu");
         ps.setObject(2,5);


        //4.执行
        ps.execute();

        //5.资源的关闭
        JDBCUtils.closeResource(conn,ps);

      /*  ps.close();
        conn.close();
*/

    }




    //向数据库表中添加一条记录
    @Test
      public void testInsert()throws Exception {
         InputStream is= ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
         Properties pros=new Properties();
         pros.load(is);
         String user=pros.getProperty("user");
         String password=pros.getProperty("password");
         String url=pros.getProperty("url");
         String driverClass=pros.getProperty("driverClass");

         //2.加载驱动
         Class.forName(driverClass);
         //3.获取链接
         Connection conn= DriverManager.getConnection(url,user,password);

   //        System.out.println(conn);

        //4.  预编译sql语句返回preparedStatement的实例
        String sql="insert into result(id,studentno,score)values(?,?,?)";//?:占位符
        PreparedStatement ps = conn.prepareStatement(sql);
        //5. 填充占位符
        ps.setInt(1,1001);
        ps.setString(2,"hello");
        ps.setDouble(3,65.5);
     //   ps.setString(3,"61.5");   数据表时间
        /*
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date date=sdf.parse("1000-01-01");
        ps.setDate(3, (java.sql.Date) new Date(date.getTime()));
    */


        //6.执行操作
        ps.execute();
        //7.资源的关闭
        ps.close();
        conn.close();
    }

}

 

 StudentForQuery.java

主要实现了通用的   查的操作,调用方法可以直接使用。

//package com.bhlc.preparedstatement;

import com.bhlc.util.JDBCUtils;
import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

/**
 * @author
 * @date 
 */

public class StudentForQuery {
    @Test
    public void testqueryForStudent(){
        String sql="select * from result where id>?";
       Student stu=queryForStudent(sql,3);
        System.out.println(stu);
        sql="select id,studentno from result where id =?";
        Student student=queryForStudent(sql,1);
        System.out.println(student);
    }
    /**
     * 针对result表的通用查询操作
     *
     *
     */
    public Student queryForStudent(String sql,Object...args) {
        Connection conn= null;
        PreparedStatement ps= null;
        ResultSet  rs = null;
        try {
            conn = JDBCUtils.getConnection();

            ps = conn.prepareStatement(sql);
            for (int i=0;i<args.length;i++){
                ps.setObject(i+1,args[i]);
            }
            rs = ps.executeQuery();
            //获取结果集的元数据ResultSetMetaDate
            ResultSetMetaData rsmd=rs.getMetaData();
            //通过  ResultSetMetaData  获取结果集中的列数
            int studentCount=rsmd.getColumnCount();
            if(rs.next()){
                Student stu=new Student();
                //处理结果集数据中的每一列
                for(int i=0;i<studentCount;i++){
                    //获取列值
                    Object studentValue=rs.getObject(i+1);
                  //  Object studentValue = rs.getObject(i + 1);
                    //获取梅格列的列明
                    String studentName=rsmd.getColumnName(i+1);


                    //给stu对象指studentnAME属性,赋值为studentvalue  通过反射
                    Field field=Student.class.getDeclaredField(studentName);
                    field.setAccessible(true);
                    field.set(stu,studentValue);

                }
                return stu;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn,ps,rs);
        }
   return  null;

    }
    @Test
    public void testQuery1() {
        Connection conn= null;
        PreparedStatement ps= null;
        ResultSet resultSet = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql="select id,studentno,score from result where id>?;";
            ps = conn.prepareStatement(sql);
            ps.setObject(1,2);

            //执行并且返回结果集
            resultSet = ps.executeQuery();
            //处理结果集
            while(resultSet.next()){//判断结果集的下一条是否有数据,如果有数据那么返回true,指针下移,否则返回false 指针上移
                //获取当前这条数据的各个字段值
                 int id=resultSet.getInt(1);
                 String studentno=resultSet.getString(2);
                 Double score=resultSet.getDouble(3);

                 //方式一
              //  System.out.println("id="+id+",studentno"+studentno+",score"+score);

                //方式二
            //    Object[] date=new Object[]{id,studentno,score};

                //方式三  将数据封装成一个对象(推荐)
                Student student=new Student(id,studentno,score);
                System.out.println(student);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            JDBCUtils.closeResource(conn,ps,resultSet);
        }



    }
}

执行查询的方法,可以看到返回结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值