反射结合JDBC实现UserInfo对象数据库查询映射演示

package _5_37;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.Statement;

import java.sql.ResultSet;

import java.lang.reflect.Method;

public class UserInfo {

private int id;

private String name;

private String pwd;

private int age;

@Override

public String toString() {

return "UserInfo [id=" + id + ", name=" + name + ", pwd=" + pwd + ", age=" + age + "]";

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String value) {

this.name = value;

}

public String getPwd() {

return pwd;

}

public void setPwd(String value) {

this.pwd = value;

}

public int getAge() {

return age;

}

public void setAge(int value) {

this.age = value;

}

}

class DBFactory {

public static Connection getDBConnection() {

Connection conn = null;

try {

Class.forName("com.mysql.jdbc.Driver");

String url = "jdbc:mysql://localhost:3306/blogsystem";

String user = "root";

String password = "yourpass";

conn = DriverManager.getConnection(url, user, password);

} catch (Exception e) {

e.printStackTrace();

}

return conn;

}

}

class DBHandle {

public static Object getObject(String className, int Id) {

Object obj = null;

try {

Statement stm = con.createStatement();

ResultSet rs = stm.executeQuery(sql);

Method[] methods = c.getMethods();

while (rs.next()) {

obj = c.newInstance();

for (Method method : methods) {

String methodName = method.getName();

if (methodName.startsWith("set")) {

String columnName = methodName.substring(3, methodName.length());

Class<?>[] params = method.getParameterTypes();

if (params[0] == String.class) {

method.invoke(obj, rs.getString(columnName));

} else if (params[0] == int.class) {

method.invoke(obj, rs.getInt(columnName));

}

}

}

}

} catch (Exception e) {

e.printStackTrace();

}

return obj;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值