怎么把数据库的其中几列显示到表格中,一般的,列用ResultSetMetaData的getColumnName取,具体元素通过rs.getString()取,但是这样都是通过循环把所有的数据全读到表格中,如果我现在只想显示其中几列要怎么做。
try
{
String sql = "SELECT * FROM test";//共有5列
st = con.createStatement();
rs = st.executeQuery(sql);
Vector columnHeads = new Vector();//列头
Vector rows = new Vector();//行元素
//通过循环取列头
try
{
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); ++i)
columnHeads.addElement(rsmd.getColumnName(i));
do
{
rows.addElement(getNextRow(rs, rsmd));//通过getNextRow方法取行元素
}
while (rs.next());
}
catch (SQLException sqlex){}
st.close();
con.close();
}
catch (SQLException sqlexcep) { }
jTable = new JTable(rows, columnHeads);//建表
//取行元素
private Vector getNextRow(ResultSet rs, ResultSetMetaData rsmd) throws SQLException
{
Vector currentRow = new Vector();
for (int i = 1; i <= rsmd.getColumnCount(); ++i)
currentRow.addElement(rs.getString(i));
return currentRow;
}这样可以把所有数据读出,但我现在只想显示第2,3,5列的数据,要怎么做?
try
{
String sql = "SELECT * FROM test";//共有5列
st = con.createStatement();
rs = st.executeQuery(sql);
Vector columnHeads = new Vector();//列头
Vector rows = new Vector();//行元素
//通过循环取列头
try
{
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); ++i)
columnHeads.addElement(rsmd.getColumnName(i));
do
{
rows.addElement(getNextRow(rs, rsmd));//通过getNextRow方法取行元素
}
while (rs.next());
}
catch (SQLException sqlex){}
st.close();
con.close();
}
catch (SQLException sqlexcep) { }
jTable = new JTable(rows, columnHeads);//建表
//取行元素
private Vector getNextRow(ResultSet rs, ResultSetMetaData rsmd) throws SQLException
{
Vector currentRow = new Vector();
for (int i = 1; i <= rsmd.getColumnCount(); ++i)
currentRow.addElement(rs.getString(i));
return currentRow;
}这样可以把所有数据读出,但我现在只想显示第2,3,5列的数据,要怎么做?
currentRow.addElement(rs.getString(3));
currentRow.addElement(rs.getString(5)); 就行了