Java反射_JDBC操作数据

</pre><p>使用反射 来操作  这里是练习反射的使用</p><p>链接数据库工具类</p><p><pre name="code" class="java">private static final String DRIVER = "com.mysql.jdbc.Driver";
	private static final String USER = "root";
	private static final String PW = "1234";
	private static final String URL="jdbc:mysql://localhost:3306/reflction";
	/**
	 * 链接数据库
	 * @return
	 */
	public static Connection getConnection(){
		try {
			Class.forName(DRIVER);
			Connection con = DriverManager.getConnection(URL, USER, PW);
			System.out.println("Connection OK .....");
			return con;
		} catch (Exception e) {
			System.out.println("Connection error...");
			e.printStackTrace();
		}
		return null;
	}

核心类

public Object getById(Class clazz, Integer id) throws Exception{
		Object obj = clazz.newInstance();//实列一个
		//创建链接
		Connection con = JdbcUtils.getConnection();
		//获取实体的名字 需要拼接 从最后一个点开始		
		String tablename = clazz.getName().substring(clazz.getName().lastIndexOf("."));
		//拼接sql 语句
		String sql = "select * from "+tablename+" where id=?";
		
		try {
			PreparedStatement psmt = con.prepareStatement(sql);
			psmt.setInt(1, id);
			//查到结果集
			ResultSet rs = psmt.executeQuery();
			//遍历结果
			while(rs.next()){
				//得到所有属性
				Field[] fields = clazz.getDeclaredFields();
				for (Field field : fields) {//遍历属性
					//获取属性名  
					String fname = field.getName();
					//获取属性类型 int
					Class type = field.getType();
					//
					Method rsGetMethod = ResultSet.class.getMethod("getObject", String.class);
					Object value = rsGetMethod.invoke(rs, fname);
					//更改修饰符权限
					field.setAccessible(true);
					field.set(obj, value);
				}
			


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值