站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2EE 专题java中如何枚举结果集中所有字段名

java中如何枚举结果集中所有字段名

摘要: java中如何枚举结果集中所有字段名


如:
...
Statement smt=conn.createStatement();
ResultSet rst=smt.executeQuery(sql);
...
通过rst.getXXX("字段名")来取得值

现在要枚举出字段名,然后用循环来取值,
请问如何实现?



请查阅 数据库元语言(metadata) 相关资料


路过,友情up...


是否放错地方了,怎么没人答!?


网上搜一下,很多.


/********************************************
格式化输出数据库记录,出自<<使用java进行SQL数据库程序设计>>
返回值为格式化的字符串
********************************************/
import java.sql.*;

class Display extends Object
{
ResultSet theResultSet;
String theResult;

public void display()
{}

public void setResult(ResultSet result)
{
theResultSet= result;
}

public String getString()
throws SQLException,NoClassDefFoundError
{
theResult= "";
ResultSetMetaData metaData= theResultSet.getMetaData();
int colcount = metaData.getColumnCount();
int colSize[]= new int[colcount];
String colLabel[]= new String[colcount];
int colType[]= new int[colcount];
String colTName[]= new String[colcount];
int colPrec[]= new int[colcount];
int colScale[]= new int[colcount];

theResult +=" ";
for(int i= 1;i<= colcount;i++)
{
colSize[i-1] = metaData.getColumnDisplaySize(i);
colLabel[i-1]= metaData.getColumnLabel(i);
colType[i-1] = metaData.getColumnType(i);
colTName[i-1]= metaData.getColumnTypeName(i);
colPrec[i-1] = metaData.getPrecision(i);
colScale[i-1]= metaData.getScale(i);

if(colSize[i-1]<1+ colLabel[i-1].length())
colSize[i-1]= 1+colLabel[i-1].length();
theResult+= rightPad(colLabel[i-1],colSize[i-1]);
}

theResult +=" ";
int row= 0;

while(theResultSet.next())
{
row++;
for(int i=1;i<= colcount;i++)
{
String colvalue= theResultSet.getString(i);
if(colvalue== null)
colvalue="";
theResult+= rightPad(colvalue,colSize[i-1]);
}
theResult+=" ";
}
theResult+=" (" +row+ "rows included) ";
return theResult;
}

private String rightPad(String s,int len)
{
int curlen= s.length();
if(curlen>len)
return repString("*",len);
return (s+repString(" ",(len-curlen)));
}

private String repString(String s,int times)
{
String result="";
for(int i=0;iresult+= s;
return result;
}
}



楼上的已经很具体了

^_^


可以通过rst.getXXX("字段名")来取得值,也可以通过rst.getXXX(int)来取得值


谢谢luotitan(泰坦)的回答
本人也找到一个更好的解法:
Statement smt=conn.createStatement();
ResultSetrst=smt.executeQuery(sql);
try {
ResultSetMetaData rmd = rst.getMetaData();
//循环枚举出所有字段名
for(int i=0;i {
//第一个字段名从1开始
String fn=rmd.getColumnName(i+1);
}

}
catch(Exception ex){...}


↑返回目录
前一篇: 关于java调用snmp的问题
后一篇: 如何用struts标签表示或的关系