我需要有关如何滚动回java返回的结果集上的下一条记录的帮助。我正在使用mysql数据库。
这是formhow事件中的代码。我在哪里加载要返回的第一个结果集:
if (rs.next()) {
jLabel5.setText(rs.getString("Question"));
jRadioButton1.setText("A. " + rs.getString("A"));
jRadioButton2.setText("B. " + rs.getString("B"));
jRadioButton3.setText("C. " + rs.getString("C"));
jRadioButton4.setText("D. " + rs.getString("D"));
}
这是按钮,它应该用于向前滚动数据库。 我需要执行rs.beforeFirst,因为jFrame上显示的内容与我要验证的变量不匹配:
try {
rs.beforeFirst();
if (rs.next()) {
jLabel5.setText(rs.getString("Question"));
jRadioButton1.setText("A. " + rs.getString("A"));
jRadioButton2.setText("B. " + rs.getString("B"));
jRadioButton3.setText("C. " + rs.getString("C"));
jRadioButton4.setText("D. " + rs.getString("D"));
if (jRadioButton1.isSelected()) {
rval = jRadioButton1.getText().charAt(0);
if (String.valueOf(rval).equalsIgnoreCase(rs.getString("Answer"))) {
JOptionPane.showMessageDialog(null, "Correct! Your answer is " + rval + " answer is: " + rs.getString("Answer"));
} else {
JOptionPane.showMessageDialog(null, "Wrong! your answer is " + rval + " answer is: " + rs.getString("Answer"));
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
我的问题是如何继续滚动浏览数据库。因为我在rs.next()之前使用rs.beforeFirst()时结果集没有进展 我也尝试过:
while(rs.next()){...}
它有效,但它没有让我选择我想要的radioButton。并且它继续执行直到结果集结束,即使没有手动点击按钮(滚动)多次。请帮我弄清楚这是什么解决方案。如果您需要更多细节,请询问。感谢。
答案 0 :(得分:1)
您不应该使用表示逻辑混合数据库访问逻辑。这只会导致紧密耦合的代码,其中两个问题只会相互冲突。数据库工作需要尽快完成。
您需要将问题分开。
首先创建一个表示数据库单行的类。
public class Question {
private String text;
private String answer;
private String optionA;
private String optionB;
private String optionC;
private String optionD;
// Add/generate c'tors/getters/setters/equals/hashcode and other boilerplate.
}
(像Eclipse这样有点像IDE可以自动生成它们)
然后创建一个执行以下JDBC作业的类:
public List<Question> list() throws SQLException {
List<Question> questions = new ArrayList<Question>();
// ...
try {
// ...
while (resultSet.next()) {
Question question = new Question();
question.setText(resultSet.getString("Question"));
question.setAnswer(resultSet.getString("Answer"));
question.setOptionA(resultSet.getString("A"));
question.setOptionB(resultSet.getString("B"));
question.setOptionC(resultSet.getString("C"));
question.setOptionD(resultSet.getString("D"));
questions.add(question);
}
} finally {
// ...
}
return questions;
}
最后只需使用List<Question>
直截了当的方式。
List<Question> questions = questionDAO.list();
int size = questions.size();
JOptionPane.showMessageDialog(null, "There are " + size + " questions!");
for (Question question : questions) {
jLabel5.setText(question.getText());
jRadioButton1.setText("A. " + question.getOptionA());
jRadioButton2.setText("B. " + question.getOptionB());
jRadioButton3.setText("C. " + question.getOptionC());
jRadioButton4.setText("D. " + question.getOptionD());
// ...
}
无需按顺序按摩结果。