在 MyEclipse 的可视化 Swing 中,有 JTable 控件。
JTable 用来显示和编辑常规二维单元表。
那么,如何将 数据库SQL中的数据绑定至JTable中呢?
在这里,提供两种方法。
/** 查询并返回记录集 */ public ResultSet getResultSet(String sql, Object[] objArr){ getConnection(); try { pStatement = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); if(objArr!=null && objArr.length>0) { for (int i = 0; i < objArr.length; i++) { pStatement.setObject(i+1, objArr[i]); } } rSet = pStatement.executeQuery(); //list = resultSetToList(rs); } catch (SQLException e) { e.printStackTrace(); } finally { //close(); } return rSet; }【注】只是与上节博客的方法名不同而已。。
/** 把结果集转成Object[][] */ public Object[][] resultSetToObjectArray(ResultSet rs) { Object[][] data = null; try { rs.last(); int rows = rs.getRow(); data = new Object[rows][]; ResultSetMetaData md = rs.getMetaData();//获取记录集的元数据 int columnCount = md.getColumnCount();//列数 rs.first(); int k = 0; while(rs.next()) { System.out.println("i"+k); Object[] row = new Object[columnCount]; for(int i=0; i<columnCount; i++) { row[i] = rs.getObject(i+1).toString(); } data[k] = row; k++; } } catch (Exception e) { } return data; }并将这两个方法存至文件UserDAO.java中。
UserDAO userDAO = new UserDAO();即可将SQL数据转化为二维数组:
Object[][] dataObjects = userDAO.resultSetToObjectArray(userDAO.getResultSet( "select id,username,password from t_userr", null));
String[] tableStrings = { "id", "username", "password" };
jTable1.setModel(new DefaultTableModel(dataObjects, tableStrings));
public static TableModel Member() { String[][] playerInfo = new String[80][8]; BaseDAO bDao = new BaseDAO(); String sql = "select id,realName,username,sex,phone,email,vocation,city from jdbctest"; String[] ss = {}; ArrayList<HashMap<Object, Object>> list = bDao.Query(sql, ss); // bDao.AllArray(list); int i = 0, j = 0; for (HashMap<Object, Object> maps : list) { Set<Object> keysObjects = maps.keySet(); for (Object kObject : keysObjects) { playerInfo[i][j] = maps.get(kObject).toString(); j++; } i++; j = 0; } String[] Names = { "id", "username", "sex", "phone","vocation","email","realName", "city" }; DefaultTableModel dModel = new DefaultTableModel(playerInfo, Names); return (TableModel)dModel; }