在Java中打印SQL查询(JTextPane):

huangapple go评论87阅读模式
英文:

Print SQL Query in Java (JTextPane)

问题

我制作了一个简单的游戏,还连接了一个数据库,一切正常运行,但我遇到问题的地方是让程序打印我制作的查询,以显示数据库中的条目(分数)

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();
}

当我运行游戏(按下按钮后会显示分数板),并且打开分数板时,我得到的文本是这样的:

> "org.sqlite.jdbc4.JDBC4PreparedStatement@691f5716"

我对Java的所有事物都相对陌生,所以我不知道这是什么意思... 有什么想法吗?

(编辑:JTP是JTextPane)

英文:

I made a simple game that is also connected to a database, everything works fine, but where I'm having issues is having the program print a query I made to show the entries in the DB (scores)

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();
		}

When I run the game (the ScoreBoard is made to show up with the press of a button) and when I open the ScoreBoard, the text I get is this:

> "org.sqlite.jdbc4.JDBC4PreparedStatement@691f5716"

I'm relatively new with all things Java, so I have no idea what this one means... any ideas?

(edit: JTP is JTextPane)

答案1

得分: 0

我希望你一切安好。
我认为问题出在你准备了语句,但是你从未执行查询并获取结果。
    PreparedStatement ps = conn.prepareStatement(sql);
    // ...执行查询...然后使用结果
    // ...
    JTP.setText("" + results.toString());

    try
    {
      // 创建MySQL数据库连接
      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";

      // 创建Java语句
      Statement st = conn.createStatement();

      // 执行查询,并获取Java结果集
      ResultSet rs = st.executeQuery(query);

      // 遍历Java结果集
      while (rs.next())
      {
        int id = rs.getInt("id");
        String score1 = rs.getString("score1");
        String score2 = rs.getString("score2");

        // 打印结果
        System.out.format("%s, %s, %s\n", id, score1, score2);
      }
      st.close();
    }
    catch (Exception e)
    {
      System.err.println("发生异常! ");
      System.err.println(e.getMessage());
    }

为了帮助你,你可以阅读更多关于Java及其对象如何与数据库进行交互的信息。

英文:

I hope you are fine.
I think the problem is you prepare the statement but never you run the query and get the results.

    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());
    }

For your help, read more about Java and his objects for interact with databases.

答案2

得分: 0

这是一种方法来执行我们的查询:

public ResultSet selectEntity(String query) {
    ResultSet result;
    try {
        PreparedStatement statement = connection.prepareStatement(query);
        result = statement.executeQuery();
    } catch (SQLException ex) {
        // 在此处理你的异常
        return null;
    }
    return result;
}

这个方法将获取查询结果并传递给我们的 JTextPane:

private void printScore() {
    // 我们调用执行查询的方法
    ResultSet resultSet = this.selectEntity("SELECT * FROM scores");
    try {
        // 我假设分数在数据库中保存为整数,所以我会使用 getInt()
        while (resultSet.next()) textPane.setText("" + resultSet.getInt(1));
    } catch (SQLException e) {
        // 在此处理你的异常
    }
}
英文:

well, the question is not clear enough. I think what you're trying to do is to get the result of a query from the DB.
This is one approach:
This method will execute our query

 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;
 }

This method will get the result of the query and pass to our 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
    }
}

huangapple
  • 本文由 发表于 2020年9月28日 06:16:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/64093813.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定