Andrew Zotov Andrew Zotov - 2 months ago 9
SQL Question

Can't get SQL query result, when using * (not column names)

I can only get results from a SQL query execution when I use

select columnname from tablename
, but not when I use
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());
}

Answer

Use ResultSet.class methods to get the desired result. You can give the column names or column index.

getInt(int columnIndex)

Retrieves the value of the designated column in the current row of this ResultSet object as an int in the Java programming language.

getString(int columnIndex)

Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language.

Here is how you can implement it:

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"); 
}
Comments