标签:select 实现 col catch sele 属性 turn prepare name
当数据库中的列名和我们java类中的属性名不相同的时候怎么实现对象的自动封装呢?
查看下面的代码:
package com.itheima.hui; import com.itheima.hui.beans.User; import com.itheima.hui.utils.JDBCUtils; import jdk.internal.org.objectweb.asm.tree.FieldInsnNode; import java.io.IOException; import java.lang.reflect.Field; import java.sql.*; public class JDBCormIgnore { public static void main(String[] args) { String sql = "select user_id userId, user_name userName,user_birthday userBirthday, user_gender userGender from user where user_id=?"; Object o = JDBCormIgnore.ignoreMatch(sql, 1); System.out.println(o); } public static Object ignoreMatch(String sql, Object... args) { Connection connect = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; //1.使用自定义工具类获得连接对象 try { connect = JDBCUtils.getConnect(); preparedStatement = connect.prepareStatement(sql); //占位符赋值操作 for (int i = 0; i < args.length; i++) { preparedStatement.setObject(i + 1, args[i]); } //执行获得结果集 resultSet = preparedStatement.executeQuery(); //根据结果集对象获得结果数据源 ResultSetMetaData metaData = resultSet.getMetaData(); int columnCount = metaData.getColumnCount();//查询结果的列数 //获取一个查询对象 if (resultSet.next()) { //创建User对象 User user = new User(); for (int i = 0; i < columnCount; i++) { //获取列的别名,如果没有别名的话就获取真实的列名 String columnLabel = metaData.getColumnLabel(i + 1); Class<User> clazz = User.class; Object value = resultSet.getObject(i + 1); Field declaredField = clazz.getDeclaredField(columnLabel); declaredField.setAccessible(true); declaredField.set(user, value); } return user; } } catch (Exception e) { e.printStackTrace(); } finally { //使用自定义工具类关闭资源 JDBCUtils.close(connect, preparedStatement, resultSet); } return null; } }
标签:select 实现 col catch sele 属性 turn prepare name
原文地址:https://www.cnblogs.com/ZYH-coder0927/p/13840273.html