目录

一.创建数据库连接和关闭资源

二.创建javaBean,用来将数据库中查询到的结果通过映射封装成对象

三.数据的查询操作

四.数据库的更新操作

五.将代码封装在测试类中并完成测试


美好的一天从白嫖开始 

 

 

一.创建数据库连接和关闭资源

package com.jdbc.JDBCUtil;

import java.sql.*;

public class JDBCUtils {
    /**
     * 获取数据库连接
     * @return 返回数据库连接对象
     * @throws Exception
     */
    public static Connection getConnection() throws Exception {
        //1,注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/jdbc_db";
        String user = "root";
        String password = "3.141592654";
        //获取数据连接对象
        Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }

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

二.创建javaBean,用来将数据库中查询到的结果通过映射封装成对象

package com.jdbc.bean;

public class User {
    private int userId;
    private String userName;

    public User() {
    }

    public User(int id, String name) {
        this.userId = id;
        this.userName = name;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + userId +
                ", name='" + userName + '\'' +
                '}';
    }
}

三.数据的查询操作

package com.jdbc.connection;

import com.jdbc.JDBCUtil.JDBCUtils;
import com.jdbc.bean.User;
import com.sun.java.accessibility.util.EventID;
import jdk.nashorn.internal.scripts.JD;
import org.junit.Test;

import javax.sql.rowset.JdbcRowSet;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

import static com.jdbc.JDBCUtil.JDBCUtils.*;

public class PrepareStatementTest {
    @Test
    public void testSelectTab() throws Exception {
        String sql = "select id userId,name userName from user_tab";
        List<User> userList = selectManyInfo(User.class, sql);
        //拉姆达表达式
        userList.forEach(System.out::println);
    }
    @Test
    public void testSelectAnyTab() throws Exception {
        String sql = "select id userId,name userName from user_tab where id = ?";
        User user = selectinfo(User.class, sql, 103);
        System.out.println(user);
    }
    @Test
    public void testUpdate(){
        String sql = "update user_tab set name = ? where id = ?";
        update(sql,"诸葛亮",102);
    }

    /**
     * 通行的方法实现增删改
     * @param sql 增删改语句
     * @param args 占位符?个数不一定,根据sql占位符的个数,传入对应数量object
     */
    public static int update(String sql,Object... args){
        int temp = -1;
        Connection conn = null;
        PreparedStatement pst = null;
        try{
            //1.获取数据库连接
            conn = getConnection();
            //2.预编译sql语句
            pst = conn.prepareStatement(sql);
            //3.填充占位符
            for (int i = 0; i < args.length; i++) {
                pst.setObject(i+1,args[i]);
            }
            //4.执行
            /*
            pst.execute();如果是查询操作返回的是true
                            如果是更新操作返回的是false;
            pst.executeUpdate();返回执行操作以后受影响的行数
             */
//            pst.execute();
            temp = pst.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //5.释放资源
            closeResource(conn,pst);
        }
        return temp;
    }

    /**
     * 查询一条记录
     * @param tClass 表对应的类对象
     * @param sql 查询语句
     * @param args 占位符,个数不定
     * @param <T> 泛型
     * @return 将查询的结果封装一个对象并返回
     * @throws Exception
     */
    public static  <T> T selectinfo(Class<T> tClass, String sql, Object... args) throws Exception {
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet res = null;
        try{
            //获取数据库连接
            conn = getConnection();
            //预编译sql语句
            pst = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                pst.setObject(i+1,args[i]);
            }
            //执行sql语句
            res = pst.executeQuery();
            //获取结果集的元数据
            ResultSetMetaData metaData = res.getMetaData();
            //获取结果集列数
            int colCount = metaData.getColumnCount();
            //处理查询结果集
            if (res.next()){
                T t = tClass.newInstance();//利用反射来创建对象,newInstance()公共方法,每个类都要求实现
                for (int i = 0; i < colCount; i++) {
                    //获取列值,列名
                    Object colValue = res.getObject(i+1);
                    String colLabel = metaData.getColumnLabel(i+1);
                    //利用反射机制来找到对应的类
                    Field field = tClass.getDeclaredField(colLabel);
                    field.setAccessible(true);
                    field.set(t,colValue);
                }
                return t;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtils.closeResource(conn,pst,res);
        }
        return null;
    }

    /**
     * 查询多条记录
     * @param tClass
     * @param sql
     * @param args
     * @param <T>
     * @return
     */
    public static <T> List<T> selectManyInfo(Class<T> tClass, String sql, Object... args){
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet res = null;
        List<T> list = new ArrayList<>();
        try {
            //获取数据库连接对象
            conn = getConnection();
            //预编译sql语句
            pst = conn.prepareStatement(sql);
            //填充占位符
            for (int i = 0; i < args.length; i++) {
                pst.setObject(i+1,args[i]);
            }
            //执行sql语句
            res = pst.executeQuery();
            //获取res的元数据,查看结果集有几列
            ResultSetMetaData metaData = res.getMetaData();
            int colCount = metaData.getColumnCount();
            //处理查询结果集
            while (res.next()){//当res不为空时,将res指针下移,并都其中的数据
                T t = tClass.newInstance();
                for (int i = 0; i < colCount; i++) {

                    //获取列名
                    String colName = metaData.getColumnLabel(i + 1);
                    //获取列值
                    Object colValue = res.getObject(i + 1);


                    //利用反射机制创建对象
                    //将获取到的列名映射User类中相应的属性上
                    Field field = User.class.getDeclaredField(colName);
                    //将该属性设置为可读
                    field.setAccessible(true);
                    //为user对象的属性字段赋值
                    field.set(t,colValue);
                }
                list.add((T) t);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtils.closeResource(conn,pst,res);
        }
    return list;
    }
}

文末有小姐姐

四.数据库的更新操作

    /**
     * 通行的方法实现增删改
     * @param sql 增删改语句
     * @param args 占位符?个数不一定,根据sql占位符的个数,传入对应数量object
     */
    public static int update(String sql,Object... args){
        int temp = -1;
        Connection conn = null;
        PreparedStatement pst = null;
        try{
            //1.获取数据库连接
            conn = getConnection();
            //2.预编译sql语句
            pst = conn.prepareStatement(sql);
            //3.填充占位符
            for (int i = 0; i < args.length; i++) {
                pst.setObject(i+1,args[i]);
            }
            //4.执行
            /*
            pst.execute();如果是查询操作返回的是true
                            如果是更新操作返回的是false;
            pst.executeUpdate();返回执行操作以后受影响的行数
             */
//            pst.execute();
            temp = pst.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //5.释放资源
            closeResource(conn,pst);
        }
        return temp;
    }

五.将代码封装在测试类中并完成测试

package com.jdbc.Test;

import com.jdbc.JDBCUtil.JDBCUtils;
import com.jdbc.bean.User;
import com.jdbc.connection.PrepareStatementTest;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
import java.util.Scanner;

import static com.jdbc.connection.PrepareStatementTest.*;

public class Test {
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户id");
        int id = scanner.nextInt();
        System.out.println("请输入用户名:");
        String password = scanner.next();
        String sql = "select id userId,name userName from user_tab where id = ? and name = ?";
        User user = PrepareStatementTest.selectinfo(User.class, sql, id, password);
        if (user == null){
            System.out.println("登录失败");
        }else {
            System.out.println("登录成功");
            Test test = new Test();
            System.out.println("请输入要执行的操作:");
            System.out.println("添加数据:1");
            System.out.println("删除数据:2");
            System.out.println("修改数据:3");
            System.out.println("添加一条数据:4");
            System.out.println("查询全部数据:5");
            int input = scanner.nextInt();
            switch (input){
                case 1:
                    test.insertInfo();
                    break;
                case 2:
                    test.deleteInfo();
                    break;
                case 3:
                    test.updateInfo();
                    break;
                case 4:
                    test.selectOneInfo();
                    break;
                case 5:
                    test.selectAll();
                    break;
                default:
                    System.out.println("输入有无,程序退出");
                    break;
            }
        }
    }
    //插入
    public void insertInfo(){
        String sql = "inset into user_tab values(?,?)";
        System.out.println("请输入要添加id:");
        Scanner scanner = new Scanner(System.in);
        int userId = scanner.nextInt();
        System.out.println("请输入要添加姓名:");
        String userName = scanner.next();
        int update = update(sql, userId, userName);
        if (update > 0){
            System.out.println("插入成功");
        }else {
            System.out.println("插入失败");
        }
    }
    //删除
    public void deleteInfo(){
        String sql = "delete from user_tab where id = ?";
        System.out.println("请输入要删除记录的id:");
        Scanner scanner = new Scanner(System.in);
        int id = scanner.nextInt();
        int update = update(sql, id);
        if (update > 0){
            System.out.println("删除成功");
        }else {
            System.out.println("删除失败");
        }
    }
    //修改
    public void updateInfo(){
        String sql = "update user_tab set set name = ? where id = ?";
        System.out.println("输入要修改的id:");
        Scanner scanner = new Scanner(System.in);
        int id = scanner.nextInt();
        System.out.println("输入用户名:");
        String userName = scanner.next();
        int update = update(sql, userName, id);
        if (update > 0){
            System.out.println("更新成功");
        }else {
            System.out.println("更新失败");
        }
    }
    //查询一条数据
    public void selectOneInfo() throws Exception {
        String sql = "select id userId,name userName from user_tab where id = ?";
        System.out.println("查询全部数据直接回车,否则输入id");
        System.out.println("输入要查询的id");
        Scanner scanner = new Scanner(System.in);
        int id = scanner.nextInt();
        User user = selectinfo(User.class, sql,id);
        if (user == null){
            System.out.println("查询结果不存在");
        }else {
            System.out.println(user);
        }
    }
    //查询全部数据
    public void selectAll() throws Exception {
        String sql = "select id userId,name userName from user_tab";
        List<User> users = selectManyInfo(User.class, sql);
        if (users.size() == 0){
            System.out.println("查询结果不存在");
        }else {
            users.forEach(System.out::println);
        }
    }

}

Logo

更多推荐