新人的一个小问题
在看视频教程学习jdbc的时候遇到了一个小问题,用的数据库是mysql。
先贴java代码
import java.sql.*;
import java.lang.reflect.*;
public class ORMTest
{
public static void main(String[] args)throws Exception
{
User user = (User)getObj("select id as Id,name as Name,birthday as Birthday,"+
"money as Money from user where id=1",User.class);
System.out.println(user);
}
public static Object getObj(String sql,Class clazz)throws Exception
{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
conn = JdbcUtils.getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
String[] colNames = new String[count];
for(int i = 1;i<=count;i++)
{
colNames[i-1] = rsmd.getColumnLabel(i);
}
Object obj = null;
if(rs.next())
{
obj = clazz.newInstance();
for(int i = 0;i<colNames.length;i++)
{
String colName = colNames[i];
String methodName = "set" + colName;
//System.out.println(methodName);
Method[] ms = obj.getClass().getMethods();
for(Method m : ms)
{
if(methodName.equals(m.getName()))
{
/*
if(methodName.equals("setId"))
m.invoke(obj,rs.getInt(colName));
else
*/
m.invoke(obj,rs.getObject(colName));
}
}
}
}
return obj;
}
finally
{
JdbcUtils.free(rs,ps,conn);
}
}
}