-1

I've learned some MySQL recently and now I'm trying to work with a database in Java. Today I've faced a problem of retrieving data from the whole column. I already know, that if i do like:

ResultSet res = st.executeQuery("SELECT * FROM table_name WHERE id = n");

I get the whole raw. And then using

ResultSetMetaData metadata = res.getMetaData();
int colCount = metadata.getColumnCount();
while (res.next()) {
            for (int i = 1; i <= colCount; i++){
                 String colValue = res.getString(i);
                 System.out.println(colValue);
            }
}

I can sysout all values of the columns of this raw.

Now I have this

 ResultSet res = st.executeQuery("SELECT column_name FROM table_name");

So I get one column and I need to iterate through it and sysout all the values.

Thanks in advance! :)

Dmitry Klimov
  • 131
  • 2
  • 4
  • 10
  • You are on the right track when going from `SELECT *` to `SELECT column_name`. [**Never** use SELECT *](http://stackoverflow.com/questions/321299/what-is-the-reason-not-to-use-select) in a programmed query. – Andreas Aug 28 '15 at 16:56

2 Answers2

1

You can do

while (res.next()) {            
      String colValue = res.getString("column_name");
      System.out.println(colValue);            
}

And it will grab the String value from that row of the result set.

Chilly
  • 578
  • 4
  • 11
0

You can directly try, if you don't know the column count then use

ResultSetMetaData metadata = res.getMetaData();

So just execute like

ResultSet res = st.executeQuery("SELECT column_name FROM table_name");
while (res.next()) {        
    String colValue = res.getString(1);
    //-------------OR--------------
    String colValue2 = res.getString("column_name");
    System.out.println(colValue);
    System.out.println(colValue2);           
}
SaviNuclear
  • 886
  • 1
  • 7
  • 19