代码之家  ›  专栏  ›  技术社区  ›  Dmitris

JDBC有一个奇怪的问题,select返回null

  •  0
  • Dmitris  · 技术社区  · 17 年前

    我真的很感激任何帮助。

    我的一些代码:

    public Result getSpecificTopic()
        {
            String query = "Select msg_body, msg_author from lawers_topic_msg";// where msg_id=2 order by msg_id desc";
             try
            {
                con = mysql.getConnection();
                //Statement stmt = con.createStatement();
                PreparedStatement stmt = con.prepareStatement(query);
                //stmt.setInt(1, topicId);
                ResultSet rs = stmt.executeQuery(query);
                int rowCount = rs.getRow();
                specificTopic = ResultSupport.toResult(rs);
    
                con.close();
                stmt.close();
            }
            catch(Exception e)
            {
            }
            return this.specificTopic;
        }
    
        public void setTopicId(String num)
        {
            this.topicId = Integer.parseInt(num);
        }
    
        public int getTopicId()
        {
            return this.topicId;
        }
    

    String query = "Select msg_body, msg_author from lawers_topic_msg";
    

    String query = "Select msg_body, msg_author from lawers_topic_msg where msg_id = " + topicId; 
    

    然后结果集不返回任何内容。。。。 我在这里发疯了,但仍然不知道问题出在哪里

    4 回复  |  直到 17 年前
        1
  •  6
  •   duffymo    17 年前

    您仍然没有正确关闭资源。这应该在finally块中完成:

    http://www.java-blog.com/correct-closing-jdbc-resources

        2
  •  3
  •   Hobo    17 年前

    还值得记录生成的SQL,并确保在直接运行数据库时实际返回您期望的数据库。

    如果你有多个数据库,那么你应该确认你正在与你认为自己是的数据库竞争——我很不好意思承认我以前就被发现过这样的情况。

        3
  •  2
  •   Makach    17 年前

    不要在这一层使用try/catch封装,尤其是因为您没有进行错误管理。this.specificTopic看起来是全局的,因此如果查询失败,它将返回this.specificTopic中存储的内容。

    也试试博比沙夫托说的话。在控制台中打印或使用调试器。这会给你一个很好的指示,说明什么是错的。

        4
  •  2
  •   Andreas Petersson    17 年前

    第二,正如马卡奇指出的,有几个问题。首先是通吃

    您不应该使用字符串连接,例如

          ....where msg_id = " + topicId;
    

    而是

          ....where msg_id = ?"
             stmt.set Int(1,topicId)
    

    编辑:看来这就是你一直在尝试的,所以有些角色很烂。

    推荐文章