Strange JDBC issue, select returns null

I am trying to use JDBC and my request works in some cases, but not in others. I would really appreciate any help.

Some of my code:

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

      

However, if I change

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

      

in

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

      

Then the results don't return anything .... I am racking my head here and still can't figure out what the problem is

0


source to share


4 answers


The first step is to make sure that no exception is thrown - at least register something in the catch () block.

It's also worth writing down the generated SQL and making sure it actually returns what you expect from the database when you start it directly.



If you have multiple databases, you should confirm that you are working against whoever you believe. I'm embarrassed to admit that I got caught earlier.

+3


source


You are still not shutting down your resources properly. This must be done in a finally block:



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

+6


source


a couple of problems with your code, I'll keep it short:

don't encrypt with try / catch at this level, especially if you're not doing error handling. this.specificTopic looks globally, so if your request fails, it will return whatever was stored in this.specificTopic.

also try what Bobby Shaftoe said. print to console or use a debugger. This should give you a good idea of โ€‹โ€‹what is wrong.

+2


source


My first guess would be Integer.parseInt (num) might throw an exception. if so, the sql expression will be broken.

secondly, as Makach noted, there are several questions. at first all the same

you shouldn't use string concatenation like

      ....where msg_id = " + topicId;

      

but rather

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

      

edit: looks like you tried anyway, SO is sucking in some characters.

+2


source







All Articles