Day4--jdbc学习代码简记(泛型返回方法)

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.Properties;

/**
 * @author nanzhi
 * @date 2024/7/18 10:45
 */
public class druid {
    public static Connection conn;
    public static PreparedStatement stmt;
    public static FileInputStream inStream;
    public static DataSource dataSource = null;

    /**
     * 创建连接
     */

    static {
        Properties properties = new Properties();
        try {
            inStream = new FileInputStream("src/jdbc.properties");
            properties.load(inStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            dataSource = DruidDataSourceFactory.createDataSource(properties);
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            conn = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }


    /**
     * 预处理
     */
    public static PreparedStatement getStmt(String sql, Object... parameters) throws SQLException {
        stmt = conn.prepareStatement(sql);
        ParameterMetaData parameterMetaData = stmt.getParameterMetaData();
        int count = parameterMetaData.getParameterCount();
        if (count != 0 && parameters != null && parameters.length == count) {
            for (int i = 0; i < count; i++) {
                stmt.setObject(i + 1, parameters[i]);
            }
        }
        return stmt;
    }

    /**
     * 增加、删除、更新操作
     */
    public static void cru(String sql, Object... obj) throws SQLException {
        getStmt(sql, obj);
        int i = stmt.executeUpdate();
        //截取表名
        String table = sql.split(" ")[0];
        System.out.print(table + "->");
        System.out.println("影响了" + i + "行数据");
    }

    /**
     * 查询操作
     */
    public static <T> void select(String sql, Object... obj) throws SQLException, ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        getStmt(sql, obj);
        ResultSet rs = stmt.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        //截取表名
        String table = sql.split(" ")[3];
        //获取反射对象
        Class cls = Class.forName(table);
        ArrayList<T> data = new ArrayList<T>();
        int count = 0;
        while (rs.next()) {
            T t = (T) cls.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 获取列值
                Object value = rs.getObject(i);
                if (value != null) {
                    // 获取列名
                    String columnName = metaData.getColumnName(i);
                    // 获取泛型对象的字段
                    Field f = cls.getDeclaredField(columnName);
                    // 设置字段可访问
                    f.setAccessible(true);
                    // 将列值设置到泛型对象的字段中
                    f.set(t, value);
                }
            }
            // 将泛型对象添加到结果列表中
            data.add(t);
            count++;
        }
        for (T item : data) {
            System.out.println(item);
        }
        System.out.println("查询了" + count + "行数据");
    }


    public static void main(String[] args) throws SQLException, NoSuchFieldException, ClassNotFoundException, InstantiationException, IllegalAccessException {
//        cru("delete from student where sno=5");
        select("select * from student");

    }
}

这里定义好表中的属性信息后就可以用Ptg插件生成的javaBean信息


public class student {
    private Integer sno;
    private String name;
    private String sex;
    private Integer age;
    private String major;

    public student() {
    }

    public student(Integer sno, String name, String sex, Integer age, String major) {
        this.sno = sno;
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.major = major;
    }

    /**
     * 获取
     * @return sno
     */
    public Integer getSno() {
        return sno;
    }

    /**
     * 设置
     * @param sno
     */
    public void setSno(Integer sno) {
        this.sno = sno;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return sex
     */
    public String getSex() {
        return sex;
    }

    /**
     * 设置
     * @param sex
     */
    public void setSex(String sex) {
        this.sex = sex;
    }

    /**
     * 获取
     * @return age
     */
    public Integer getAge() {
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(Integer age) {
        this.age = age;
    }

    /**
     * 获取
     * @return major
     */
    public String getMajor() {
        return major;
    }

    /**
     * 设置
     * @param major
     */
    public void setMajor(String major) {
        this.major = major;
    }

    public String toString() {
        return "student{sno = " + sno + ", name = " + name + ", sex = " + sex + ", age = " + age + ", major = " + major + "}";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT ·南栀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值