Note that there are some explanatory texts on larger screens.

plurals
  1. POretrieving values from database in java
    text
    copied!<p>I am making a program that retrieves the inputted data/values of fields from the database I created. But when I'm running it the output is always null. I wonder what's wrong? Here's my code:</p> <pre><code>import java.sql.*; public class GuestsInfo { private String firstName, lastName; private int age; private Connection con; private PreparedStatement statement; public GuestsInfo() { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/3moronsdb","root",""); } catch (Exception e) { e.printStackTrace(); } } public GuestsInfo(String firstName, String lastName, int age) { this(); try { statement = con.prepareStatement("Insert into guest(firstName,lastName,age)values(?,?,?)"); statement.setString(1, firstName); statement.setString(2, lastName); statement.setInt(3, age); statement.executeUpdate(); con.close(); } catch(Exception e) { e.printStackTrace(); return; } } public void setFirstName(String firstName) { try{ statement= con.prepareStatement("SELECT * FROM guest WHERE firstName = ?"); statement.setString(1, firstName); ResultSet rs = statement.executeQuery(); while(rs.next()){ firstName = rs.getString(1); } }catch(Exception e){ System.out.print(e); } } public String getFirstName(){ return firstName; } public void setLastName(String lastName) { try{ statement= con.prepareStatement("SELECT * FROM guest WHERE lastName = ?"); statement.setString(2, lastName); ResultSet rs = statement.executeQuery(); while(rs.next()){ lastName = rs.getString(2); } }catch(Exception e){ System.out.print(e); } } public String getLastName(){ return lastName; } public void setAge(int age){ try{ statement = con.prepareStatement("SELECT * FROM guest WHERE age=?"); statement.setInt(3, age); ResultSet rs = statement.executeQuery(); while(rs.next()){ age = rs.getInt(3); } }catch(Exception e){ System.out.print(e); } } public int getAge(){ return age; } </code></pre> <p>In my main class I have this codes:</p> <pre><code> public class TestMain { public static void main(String [] args){ GuestsInfo gi = new GuestsInfo(); gi.setFirstName("Ericka"); System.out.println(gi.getFirstName()); } } </code></pre> <p>I wonder why it always says null when I'm running it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload