使用*(不是列名)时无法获取SQL查询结果

时间:2016-09-28 19:05:01

标签: java sql jdbc

我只能在使用select columnname from tablename时从SQL查询执行中获得结果,但在使用select * from tablename

时则不能
public static void connectAndExecute(String host, String uName, String uPass, String sqlQuerry){
    try { 
        DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    } catch (SQLException e) {          
        e.printStackTrace();
    }
    try{
    Connection con=DriverManager.getConnection( host, uName, uPass);
    String[] conData = null;
    Statement stmt = null;      
    try {
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sqlQuerry);
        /*this is the place of my problem*/
    } 
        catch (SQLException e) {            
        e.printStackTrace();
    }
    }
    catch (SQLException err){
        System.out.println(err.getMessage());
    }

1 个答案:

答案 0 :(得分:1)

使用ResultSet.class方法获得所需的结果。您可以指定列名称或列索引。

getInt(int columnIndex)

  

检索当前行中指定列的值   此ResultSet对象作为Java编程语言中的int。

getString(int columnIndex)

  

检索当前行中指定列的值   此ResultSet对象为Java编程语言中的String。

以下是如何实施它:

while(rs.next()){ 
//Retrieve by column index 
int id = rs.getInt(1); //assume id is at 1st index
int age = rs.getInt(4); //assume age is at 4th index
String first = rs.getString(2); // assume first name is at 2nd index
String last = rs.getString(3); // assume last name is at 3rd index
//Display values 
System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last);
System.out.println(" End of one row"); 
}