将JDBC ResultSet结果集转成List

package test;

import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.PreparedStatement;  
import java.sql.SQLException;
public class DBHelper {
     public static final String url = "jdbc:mysql://127.0.0.1/peixian";  
        public static final String name = "com.mysql.jdbc.Driver";  
        public static final String user = "root";  
        public static final String password = "root";
     
        public Connection conn = null;  
        public PreparedStatement pst = null;  
     
        public  DBHelper(String sql) {  
            try {  
                Class.forName(name);//指定连接类型  
                conn = DriverManager.getConnection(url,user,password);//获取连接  
                pst = conn.prepareStatement(sql);//准备执行语句  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
     
        public void close() {  
            try {  
                this.conn.close();  
                this.pst.close();  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
        }
   
}
//==============执行demo
package test;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Demo {  
    static String sql = null;  
    static DBHelper db1 = null;  
    static ResultSet ret = null;  
    
    public static void main(String[] args) {  
        sql = "select *from xy_sys_menu";//SQL语句  
        db1 = new DBHelper(sql);//创建DBHelper对象
        
        try {  
            List<Map<String,Object>>list=new ArrayList<Map<String,Object>>();
            ret = db1.pst.executeQuery();//执行语句,得到结果集  
            ResultSetMetaData md = ret.getMetaData(); //获得结果集结构信息,元数据
            int columnCount = md.getColumnCount();   //获得列数 
            while (ret.next()) {
                Map<String,Object> rowData = new HashMap<String,Object>();
                for (int i = 1; i <= columnCount; i++) {
                    rowData.put(md.getColumnName(i), ret.getObject(i));
                }
                list.add(rowData);
     
            }
            System.out.println("list============="+list);
            ret.close();  
            db1.close();//关闭连接  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
    }
    
}

 

将JDBC ResultSet结果集转成List

上一篇:MySQL 常用语法


下一篇:plsql developer中,清除登录历史