我有一个连接并加载数据库的方法。它将所有带有分数的用户名保存到ResultSet中。目前,我只能让它逐行打印到控制台。如何将整个ResultSet保存到String中,以便将其打印到JTextField中?
模特课程:
function RefreshSessions()
{
var req = new XMLHttpRequest();
req.onreadystatechange = function()
{
if(req.readyState == 4 && req.status == 200)
{
document.getElementById('EmptyDiv').innerHTML = req.responseText;
}
}
req.open('GET', 'update_sessions.php', true);
req.send();
}
setInterval(function(){RefreshSessions()}, 1000);
控制器类:
public static void loadDatabase() {
try {
getDb().connectDB();
getDb().createDB();
ResultSet rs = getDb().getScores();
while (rs.next()) {
System.out.print("Username: "+rs.getString(1));
System.out.println(" Score: "+rs.getString(2));
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
getInstructions()是一个JTextArea。我想这一行:
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == view.getSubmitButton()) {
Model.getDb().insertScores(view.getUsernameTextField().getText(), Model.getScore()); //insert scores into table
view.getInstructions().setText("Scores: ");
}
}
显示完整的分数列表
答案 0 :(得分:2)
您可以使用所需的文本返回loadDatabase()
中的字符串:
public static String loadDatabase()
在内部,您只需将这些结果保存到字符串:
,而不是打印到控制台StringBuilder resultText = new StringBuilder();
while (rs.next()) {
resultText.append("Username: ").append(rs.getString(1)).append(" Score: ").append(rs.getString(2));
}
return resultText.toString();
然后,您需要在loadDatabase()
之前调用view.getInstructions().setText("Scores: ");
并将其添加到该setText。
答案 1 :(得分:0)
没有比这更简单的了。迭代时使用StringBuilder连接字符串:
final StringBuilder builder = new StringBuilder();
while( rs.next() ) {
builder
.append("Username: ").append( rs.getString(1) )
.append( "Score: " ).append( rs.toString(2) )
;
}
String allResults = builder.toString();
但是:在问这个问题之前你问了谷歌吗?
答案 2 :(得分:-2)
在loadDatabase()
内:
而不是
while (rs.next()) {
System.out.print("Username: "+rs.getString(1));
System.out.println(" Score: "+rs.getString(2));
}
你应该把:
String[] arrayofScores = null;
while (rs.next()) {
String score= rs.getString(2);
arrayofScores = score.split("\n");
for (int i =0; i < arr.length; i++){
System.out.println(arrayofScores [i]);
}
}
或者你可以使用StringBuilder作为@Alex GS建议