如何解决使用JavaJTextPane打印SQL查询
我制作了一个也连接到数据库的简单游戏,一切正常,但是我遇到问题的地方是让程序打印了一个查询,以显示数据库中的条目(分数)
String sql = "select * from scores";
try {
PreparedStatement ps =
conn.prepareStatement(sql);
JTP.setText(""+ps.toString());
} catch (sqlException e1) {
// Todo Auto-generated catch block
e1.printstacktrace();
}
运行游戏时(按一下按钮即可显示scoreBoard),当我打开scoreBoard时,得到的文本是:
“ org.sqlite.jdbc4.JDBC4PreparedStatement@691f5716”
我对Java的所有事物都比较陌生,所以我不知道这意味着什么...任何想法?
(编辑:JTP是JTextPane)
解决方法
我希望你一切都好。 我认为问题是您准备了语句,但从未运行查询并获得结果。
PreparedStatement ps = conn.prepareStatement(sql);
...you run the query.. an then use the results
...
JTP.setText(""+results.toString());
try
{
// create our mysql database connection
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://localhost/test";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl,"root","");
String query = "SELECT * FROM SCORES";
// create the java statement
Statement st = conn.createStatement();
// execute the query,and get a java resultset
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
while (rs.next())
{
int id = rs.getInt("id");
String score1 = rs.getString("score1");
String score2 = rs.getString("score2");
// print the results
System.out.format("%s,%s,%s\n",id,score1,score2);
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
在您的帮助下,请阅读有关Java及其与数据库交互的对象的更多信息。
,嗯,这个问题还不够清楚。我认为您正在尝试做的是从数据库获取查询结果。 这是一种方法: 此方法将执行我们的查询
public ResultSet selectEntity(String query) {
ResultSet result;
try {
PreparedStatement statement = connection.prepareStatement(query);
result = statement.executeQuery();
} catch (SQLException ex) {
//handle your exception here
return null;
}
return result;
}
此方法将获取查询结果并传递给我们的JTextPane
private void printScore()
{
//we're calling the method that executes the query
ResultSet resultSet = this.selectEntity("SELECT * FROM scores");
try {
// I assume that the score is saved as Integer in the DB,so I'll use **getInt()**
while(resultSet.next()) textPane.setText(""+resultSet.getInt(1));
} catch (SQLException e) {
//handle your exception here
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。