我有以下代码,其中请求从浏览器通过休息Web服务到控制器,然后通过jdbc建立数据库连接,我的查询是我想以这样的方式更改我的下面的代码,以便它可以检索表的所有列,请告知我如何实现相同的
@GET
@Produces(MediaType.TEXT_HTML)
public String retriveData(@QueryParam("tablename") String tablename) throws SQLException
{
Connection con=null;
PreparedStatement ps=null;
String statement="";
String retString="";
try {
//Class.forName("com.mysql.jdbc.Driver");
//put sql jdbc jar in tomcat lib
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println(" ******Driver Loaded *******");
con=DriverManager.getConnection("jdbc:sqlserver://sv53720.hk.sunlife:1433; databaseName=pin_uat", "pinread","pinread123");
con.setAutoCommit(false);
System.out.println(" ******Connected To MSSql ******");
System.out.println("FROM TABLE NAME : "+tablename);
statement="SELECT * FROM "+tablename+";";
System.out.println("STATEMENT : "+statement);
ps=con.prepareStatement(statement);
// Turn use of the cursor on.
//ps.setFetchSize(50);
ps.setMaxRows(10);
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
String name=rsmd.getColumnName(1);
while(rs.next())
{
retString=retString+name+" : "+rs.getString(name)+"<br>";
System.out.println(retString);
}
System.out.println("Table FOUND!!!");
ps.close();
rs.close();
con.close();
return retString;
}catch(Exception e) {
e.printStackTrace();
}
finally {
if(con!=null)
con.close();
}
return "Unable To Read Table :(";
}
答案 0 :(得分:0)
试试这个
statement="SELECT * FROM "+tablename+";";
ps=obj.getConnection().prepareStatement(statement);
ps.setMaxRows(10);
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// The column count starts from 1
for (int i = 1; i <= columnCount; i++ ) {
String name = rsmd.getColumnName(i);
retString=retString+i+"- coloum name="+name+",";
}
System.out.println(retString);