jdbc总结(四)

2014-11-24 07:23:22 · 作者: · 浏览: 1
ColumnCount();
String[] colNames = new String[count];
for(int i = 1; i < colNames.length;i++){
colNames[i-1] = rsmd.getColumnName(i);
}
List> datas = newArrayList>();
// 5.处理结果
while (rs.next()) {// 按行来遍历,将每一行添加到map中,list中最后存放的是表
Map data = new HashMap();
for(inti = 1;i<= colNames.length;i++){
data.put(colNames[i-1],rs.getObject(i));
}
datas.add(data);
}
return datas;
} finally {
JdbcUtils.free(rs, ps, conn);
}
}

}

11. 对象与关系的映射(利用反射)
[java]
public class ORMTest {

/**
* @param args
* @throwsInvocationTargetException
* @throwsIllegalAccessException
* @throws SQLException
* @throwsIllegalArgumentException
* @throws InstantiationException
*/
public static void main(String[] args) throws IllegalArgumentException,
SQLException, IllegalAccessException,InvocationTargetException,
InstantiationException {

User user = (User) getObject(
"select idas Id ,name as Name, birthday as Birthday,money as Money from user whereid=2",
User.class);
System.out.println(user);
}

static ObjectgetObject(String sql, Class clazz) throws SQLException,
IllegalArgumentException, IllegalAccessException,
InvocationTargetException, InstantiationException {
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 <= colNames.length; i++) {
colNames[i - 1] = rsmd.getColumnLabel(i);
}

Object object = null;
Method[] ms = clazz.getMethods();

// 5.处理结果
if (rs.next()) {// 按行来遍历,将每一行添加到map中,list中最后存放的是表
object = clazz.newInstance();
for (int i = 0; i < colNames.length; i++) {
String colName = colNames[i];
String methodName = "set" + colName;
// System.out.println(methodName);
for (Method m : ms) {
if (methodName.equals(m.getName())) {
m.invoke(object, rs.getObject(colName));
}
}
}
}
return object;
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
}


12. 创建数据库连接池,先创建多个连接,将连接一次放在List的尾部,用的时候从List的头部取出连接,使用连接;用完释放连接的时候是将连接返回到连接池的尾部,供后边的用户使用。达到连接重复使用的目地。
[java]
/**
*
* 创建数据库连接池
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;

public class MyDataSource {

private static String url = "jdbc:mysql://localhost:3306/jdbc";
private static String user = "root";
private static String password = "mysql";


private LinkedListconnectionsPoll = new LinkedList();
public MyDataSource(){
for(int i = 0; i<5;i++){
try {
this.conn