如何将数据库查询返回的resultset转化成List形式返回
就是一个resultSet转为List.
·
1.先写一个数据源的工具类
package com.sunshine.util;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class SessionFactory {
DataSource dataSource;
public SessionFactory(){
//创建连接池
DriverManagerDataSource source = new DriverManagerDataSource();
source.setDriverClassName("com.mysql.jdbc.Driver");
//账号和密码
source.setUsername("root");
source.setPassword("root");
//所要查数据库
source.setUrl("jdbc:mysql://localhost:3306/mydb1?serverTimezone=Asia/Shanghai");
dataSource=source;
}
//创建连接的办法
public Session createSession(){
Connection connection = null;
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
return new Session(connection);
}
}
2.在写一个将resultSet转为List的工具类
package com.sunshine.util;
import lombok.extern.slf4j.Slf4j;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.*;
@Slf4j(topic = "e")
public class ResultSetUtil {
public static List<Map> resultSetToList(ResultSet rs) throws java.sql.SQLException {
if (rs == null)
return Collections.EMPTY_LIST;
ResultSetMetaData md = rs.getMetaData(); //得到结果集(rs)的结构信息,比如字段数、字段名等
int columnCount = md.getColumnCount(); //返回此 ResultSet 对象中的列数
List<Map> list = new ArrayList<Map>();
Map rowData = new HashMap();
while (rs.next()) {
rowData = new HashMap(columnCount);
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnName(i).toLowerCase(), rs.getObject(i));
}
list.add(rowData);
log.debug("list:"+list.toString());
}
return list;
}
}
3.在写一个测试类TestMybatis
package com.sunshine.test;
import com.sunshine.session.Session;
import com.sunshine.util.ResultSetUtil;
import com.sunshine.util.SessionFactory;
import lombok.extern.slf4j.Slf4j;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Slf4j(topic = "e")
public class TestMybatis {
public static void main(String[] args) {
try {
String sql = "select * from emp";
//获得Session对象
Session session = new SessionFactory().createSession();
//通过Session对象获得连接对象
Connection connection =session.getConnection();
//进行预编译
PreparedStatement psmt = connection.prepareStatement(sql);
ResultSet res = psmt.executeQuery();
//调用方法将resultSet转为List
List list = ResultSetUtil.resultSetToList(res);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)