JavaSE(二十一)JDBC

本文详细介绍了如何通过JDBC连接MySQL数据库,包括引入jar包、配置连接参数、创建数据库连接对象,以及封装方法执行插入、更新和查询操作。
摘要由CSDN通过智能技术生成

JDBC

  • mysql

JDBC使用步骤

1,引入第三方的jar包

2,获取数据库连接对象

配置文件 db.properties

driveClassName=com.mysql.cj.jdbc.Driver
userName=root
password=123456
url=jdbc:mysql://127.0.0.1:3306/db1

private static Properties properties = new Properties();
​
    //在类加载时刻执行 而且只执行一次 提前加载资源
    static {
        try {
            properties.load(new FileInputStream("./res/db.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
​
    /**
     * 获取数据库连接对象
     */
    public static Connection getConn() {
//        Driver driver; //Sun公司定义接口 厂商写具体实现类
        Connection connection = null;
        try {
            //1,加载驱动 把驱动类加载进JVM;Class.forName("驱动类的全路径")是获取类对象
            Class.forName(properties.getProperty("driveClassName"));
            //2 获取数据库连接对象 向上转型  jdbc:mysql是连接协议名称 3306是MySQL的端口号  db1是数据库的名称
            connection = DriverManager.getConnection(
                    properties.getProperty("url"),
                    properties.getProperty("userName"),
                    properties.getProperty("password"));
            System.out.println(connection);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

3,封装方法执行更新语句

/**
     * INSERT INTO tb_bank_account(name,password,balance) VALUES(?,?,?);
     *
     * @param sql
     * @return
     * @throws SQLException
     */
    // insert delete update :返回值都是int值 记录被修改的数量
    public static int updateSql(String sql, Object... paras) throws SQLException {
        //1,获取数据库连接对象
        Connection conn = getConn();
        //2, PreparedStatement语句对象 用于执行SQL语句
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        //3,给占位符赋值
        for (int i = 0; i < paras.length; i++) {
            preparedStatement.setObject(i + 1, paras[i]);
        }
        //4,执行SQL
        int i = preparedStatement.executeUpdate();
        System.out.println("记录被修改的数量: " + i);
        return i;
    }

4,封装方法执行查询语句

// select 虚拟表 返回值: 结果集合
    //Select * from tb where id=?;
    public static <T> List<T> selectSql(Class<T> tClass, String sql, Object... paras) throws SQLException, IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
        //1 获取连接对象
        Connection conn = getConn();
        //2 生成语句对象
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        //3 给占位符赋值
        for (int i = 0; i < paras.length; i++) {
            preparedStatement.setObject(i + 1, paras[i]);
        }
        //4 执行 获取的是结果集合
        ResultSet resultSet = preparedStatement.executeQuery();
        //描述信息 元数据
        int columnCount = resultSet.getMetaData().getColumnCount();
        List<T> list = new ArrayList<>();
        //5 结果集的处理 resultSet.next()返回值为true 表示有下一行数据 否则就是遍历完了
        while (resultSet.next()) {
            //根据反射创建对象 无参构造
            T t = tClass.newInstance();
            for (int i = 1; i <= columnCount; i++) {
                //获取此行 此纪录 的每个字段的值
                //获取列的 字段的名称 id name
                String columnName = resultSet.getMetaData().getColumnName(i);
                //拼接set方法名称
                String methodName = "set" + columnName.substring(0, 1).toUpperCase() + columnName.substring(1);
                // 类型名称: 此类型的全路径 java.lang.String
                String columnClassName = resultSet.getMetaData().getColumnClassName(i);
                // 方法对象  setId setName setPassword setBalance
                Method method = tClass.getMethod(methodName, Class.forName(columnClassName));
                //调用方法
                method.invoke(t, resultSet.getObject(i));
            }
            //放入集合中
            list.add(t);
        }
        return list;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值