I developed a method to query a database and return the specific values that I'm looking for except that the value being returned is the last value. In my while loop I can do a system.out.println(answers)and I can see all of the values, my return answers only returns the last value.
Any ideas?
public String getAnswers() throws DAOException, SQLException{
//This still needs work
String testName = "Test", formName = "Form";
String sql = "select item, itemkey from dbo.TestMaster " +
"where TestName = ? and FormName = ? " +
"order by item ";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String answers = null;
try {
//Define the db to connect to
String dbConnect = "jdbc:sqlserver://MPSQL8B\\INST2;DatabaseName=iTest_Qa_UT;" + " integratedSecurity=false;";
//Fetch the sql class
String driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
//Create new instance of class
try {
Class.forName(driverClass).newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Define User name and password...
String uName = "asdasd";
String pWord = "asdasd";
//Connection result = null;
//Login to the db
conn = DriverManager.getConnection(dbConnect, uName, pWord);
//Statement to submit sql
ps = conn.prepareStatement(sql);
ps.setString(1, testName);
ps.setString(2, formName);
rs = ps.executeQuery();
while ( rs.next() ) {
answers = rs.getString("itemKey");
System.out.println(answers);
}
}finally {
release(rs, ps, conn);
}
return answers;
}