2014-08-31 17:34:33

Swing JTable 动态SQL语句查询

写了无数次了,保存起来下次不重写了。每执行一次查询更新一次table的表头和表行数据。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton1ActionPerformed
		ResultSet rs = DBUtil.executeQuery(textField1.getText());//执行SQL语句
		// jTable1 = new JTable();
		try {
			List<List<Object>> ls = new ArrayList<List<Object>>();
			List<String> column = new ArrayList<String>();
			ResultSetMetaData rsm = rs.getMetaData();//获取表元数据
			for (int i = 1; i < rsm.getColumnCount()+1; i++) {
				column.add(rsm.getColumnName(i));
			}
			while (rs.next()) {
				List<Object> result = new ArrayList<Object>();
				for (int i = 1; i < rsm.getColumnCount()+1; i++) {
					result.add(rs.getObject(i));
				}
				ls.add(result);
			}
			Object[][] obj = new Object[ls.size()][column.size()];
			for (int i = 0; i < ls.size(); i++) {
				List<Object> a = ls.get(i);
				for (int j = 0; j < column.size(); j++) {
					System.out.println(a.get(j));
					obj[i][j] = a.get(j);
				}
			}
			jTable1.setModel(new DefaultTableModel(obj,column.toArray(new String[column.size()])));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
发表回复