簡體   English   中英

在 Java 中打印 SQL 查詢 (JTextPane)

[英]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)

我希望你們都很好。 我認為問題在於您准備了語句,但從未運行查詢並獲得結果。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM