title: Java method - Returning the contents of a Database column in a string
body: <p>I'm new to Java so any help is appreciated! I've written a method that returns the contents of a table in my database. The table is called "messages".
  I am trying to get the contents of this tables one column to be returned by my method as a string so I can then display it in an application.</p>
  
  <p>Here is my method:</p>
  
  <pre><code>public String readData() {
  
      try {
          String query = "select * from messages";
          PreparedStatement pstmt = ConnectionBuilder.buildConnection().prepareStatement(query);
          ResultSet rs = pstmt.executeQuery("select * from messages");
          while (rs.next()){
          String data = rs.getString("MESSAGE");
  
              System.out.println(data);
          }
  
      } catch (Exception e) {
          System.out.println(e);
      }
      return data;
  
  }
  </code></pre>
  
  <p>The System.out.println(data); line correctly displays what I want:</p>
  
  <pre><code>Hello!
  Hello!
  Hello!
  Hello!
  Hello!
  Hello!
  hio
  hio
  hio
  Testerrr
  </code></pre>
  
  <p>But the return data; says that data "cannot be resolved to a variable"</p>
  
  <p>Where am I going wrong! I tried to declare the variable at the top of the method but it is still returning null:</p>
  
  <pre><code>public String readData() {
      String data = null;
      try {
          String query = "select * from messages";
          PreparedStatement pstmt = ConnectionBuilder.buildConnection().prepareStatement(query);
          ResultSet rs = pstmt.executeQuery("select * from messages");
          while (rs.next()){
          data = rs.getString("MESSAGE");
          }
  
      } catch (Exception e) {
          System.out.println(e);
      }
      System.out.println(data);
      return data;
  
  }
  </code></pre>