package YouBiao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TestYouBiao { static String className="com.mysql.jdbc.Driver"; static String url="jdbc:mysql://127.0.0.1/pei_test"; static String user="root"; static String passWord="123456"; static String sql="select * from blade_dept"; public static void test() { try { Class.forName(className); Connection conn=DriverManager.getConnection(url, user, passWord); PreparedStatement prs=conn.prepareStatement(sql); ResultSet rs=prs.executeQuery(); List<Map<String,Object>>list=new ArrayList<Map<String,Object>>(); ResultSetMetaData rsd=rs.getMetaData(); int columnCount=rsd.getColumnCount(); while(rs.next()) { Map<String,Object>map=new HashMap<String, Object>(); for(int i=1;i<columnCount;i++) { map.put(rsd.getColumnName(i), rs.getObject(i)); } list.add(map); } System.out.println("list======"+list); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { test(); } }
package YouBiao; public interface IYouBiao { static String url = "jdbc:mysql://127.0.0.1/pei_test"; static String name = "com.mysql.jdbc.Driver"; static String user = "root"; static String password = "123456"; static String sql="select * from blade_dept"; }
package YouBiao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TestYouBiao { public static Connection conn=null; public static PreparedStatement ps=null; static ResultSet ret = null; public static List<Map<String,Object>> test() { try { Class.forName(IYouBiao.name); conn=DriverManager.getConnection(IYouBiao.url,IYouBiao.user, IYouBiao.password); ps=conn.prepareStatement(IYouBiao.sql); ret=ps.executeQuery(); System.out.println("ret================"+ret); List<Map<String,Object>>list=new ArrayList<Map<String,Object>>(); 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); return list; } catch (Exception e) { e.printStackTrace(); } return null; } public static void main(String[] args) { List<Map<String,Object>>list=test(); System.out.println("list====="+list); } }