package com.briup.jdbctest; import java.lang.reflect.Field; import java.math.BigDecimal; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class JDBCUtils { private static Connection conn = null; // 连接对象 private static String driver = "oracle.jdbc.driver.OracleDriver"; // jar包中的OracleDriver中的类 private static String url = "jdbc:oracle:thin:@//127.0.0.1:1521/orcl"; private static String username = "scott"; private static String password = "tiger"; private static PreparedStatement ps = null; private static ResultSet rs = null; public static Connection getConnection() { try { Class.forName(driver); conn = DriverManager.getConnection(url, username, password); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } // 将表中的数据封装成所有对象 /** * * @param <T> 封装对象的泛型 * @param clazz * @param sql sql语句 * @param args 给预编译语句传参 * @return */ public static <T> List<T> queryToObj(Class<T> clazz, Connection conn, String sql, Object... args) { try { // 1. 获取结果集 ps = conn.prepareStatement(sql); for (int i = 1; i <= args.length; i++) { ps.setObject(i, args[i - 1]); } rs = ps.executeQuery(); // 2. 将查询的结果和字段名称获取 获取所有的字段 ResultSetMetaData metaData = rs.getMetaData(); // 用来保存对象的 ArrayList<T> cols = new ArrayList<>(); while (rs.next()) { // 创建对象 T obj = clazz.newInstance(); for (int i = 1; i <= metaData.getColumnCount(); i++) { // 通过反射获取对应的字段 Field filed = clazz.getDeclaredField(metaData.getColumnLabel(i).toLowerCase()); filed.setAccessible(true); Object value = rs.getObject(metaData.getColumnLabel(i)); // oralce的number 在java中的是BigDecimal if (value instanceof BigDecimal) { value = ((BigDecimal) value).intValue(); } filed.set(obj, value); } cols.add(obj); } return cols; } catch (Exception e) { e.printStackTrace(); } finally { Close(conn, ps, rs); } return null; } // 释放资源 private static void Close(Connection conn, PreparedStatement ps, ResultSet rs) { if (conn != null) { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (rs != null) { try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) { Connection connection = getConnection(); String sql = "select * from stu where id=? or id=?"; List<Stu> list = queryToObj(Stu.class, connection, sql, 1, 2); for (Stu stu : list) { System.out.println(stu); } } }
原文地址:https://www.cnblogs.com/codlover/p/11491020.html
时间: 2024-10-15 23:41:08