0

I'm using MySQL commands via JDBC (Java) to make changes to my database. I have implemented the following method to return the values of a column. The goal is to have the location in the column (row) correspond with their location in the array (index). This works with String columns, but with numerical columns, the ResultSet seems to place them in ascending order, thus making their positioning in the returned String array not reflect their positioning in the column. 'rs' is a ResultSet reference variable.

public String[] getColumnContents(String tableName, String columnName) {
    String sql = "SELECT " + columnName + " FROM " + tableName;
    String[] results = new String[SQLManager.getColumnLength(tableName, columnName)];

    try {
       rs = statement.executeQuery(sql);

       for (int counter = 0; rs.next(); counter++) {
            results[counter] = rs.getString(columnName);
       }

    } catch (SQLException e) {
       e.printStackTrace();
    }

    return results;

}
4
  • when you are dealing with numerical columns why are using rs.getString ? Commented Nov 25, 2012 at 4:44
  • Because this method is used to return the values of columns of multiple data types. Commented Nov 25, 2012 at 4:49
  • 2
    You can use getObject() instead Commented Nov 25, 2012 at 4:54
  • What exactly does getColumnLength() do? The counter in your loop counts the rows returned by the query. You cannot know how many rows the ResultSet will return, so I doubt getColumnLengt() really calculates the number ofr rows. You should use a dynamically adjusting List instead of a fixed sized array when dealing with result sets from the database. Commented Nov 25, 2012 at 8:56

1 Answer 1

1

It's as simple as adding an ORDER BY clause to the SQL command. Here's my working method:

public String[] getColumnContents(String tableName, String columnName) {
String sql = "SELECT " + columnName + " FROM " + tableName + " ORDER BY " + columnName1 + " ASC, " + columnName2 + " ASC";

String[] results = new String[SQLManager.getColumnLength(tableName, columnName)];

try {
    rs = statement.executeQuery(sql);

    for (int counter = 0; rs.next(); counter++) {
        results[counter] = rs.getString(columnName);
    }
} catch (SQLException e) {
    e.printStackTrace();
}

return results;

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.