簡體   English   中英

無法使用JDBC連接進行計數

[英]Not able to get count using JDBC connection

我無法通過查詢獲得行數。 我已經使用了JDBC連接。 但是,它不會顯示任何錯誤,但是會停止執行該過程。

這是我的代碼

Transaction transaction=null;
    Connection c = null;
    Statement stmt = null;
    ResultSet result;
    try {
         Class.forName("org.postgresql.Driver");
         c = DriverManager.getConnection(
         "jdbc:postgresql://192.168.1.7:5432/"+userDB,
     "postgres", "openerp");
     } catch (Exception e) {
         e.printStackTrace();
         System.err.println(e.getClass().getName() + ": " + e.getMessage());
         System.exit(0);
     }
    int count = 0;
    try {   
        LOGGER.info("In try of get");
        factory = HibernateUtil.connectDB(userDB);
        LOGGER.info("Connected to DB");
        //Open Session
        session = factory.openSession();
        //Begin Transaction
        transaction = session.beginTransaction();
        LOGGER.info("Beginning the transaction");
        stmt = c.createStatement();
        String sql = "SELECT COUNT(*) FROM mycontent_messages where status = '0'";

        count = stmt.executeUpdate(sql);
        LOGGER.info("successfully got count : "+count);
        c.commit();
        stmt.close();
        c.close();   

我得到的例外是

org.postgresql.util.PSQLException: A result was returned when none was expected.
at    org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:307)
at net.vsspl.mycontent.daoimpl.contentImpl.getUnreadCount(contentImpl.java:379)
at net.vsspl.mycontent.services.countUnreadMessages.main(countUnreadMessages.java:49)

它記錄到“開始交易”。 在那之后它什么都不顯示。 我的代碼有什么問題嗎?

您想從查詢中獲取結果集並以這種方式處理它,而不是獲取受影響的行數。

ResultSet rs =  stmt.executeQuery(sql);
 int count = 0;
 if(rs.next())
 {
    count = rs.getInt(1);
  }

計數= stmt.executeUpdate(sql);

您沒有執行更新; 您正在執行查詢。

在這里,您正在執行查詢以獲取記錄數,因此您應該使用

resultSet = stmt.executeQuery(sql);

暫無
暫無

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

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