开发者

Why is my SQL query failing?

开发者 https://www.devze.com 2023-02-20 18:02 出处:网络
I have this table: sportman { code int primary key, date Date. } containing values code 10,30开发者_如何学JAVA,50.

I have this table:

sportman
{
    code int primary key,
    date Date.
}

containing values

code 10,          30开发者_如何学JAVA,         50.
date 1990-02-15,  1999-02-15, 2010-02-15.

I wrote this query in NetBeans:

 resultSet = statement.executeQuery("select code from sportman "
                                    + "where date =  1990-02-15";

but the resultset is empty. What is the problem and how can I solve it?

 while(resultSet.next())
                      {
                             x = resultSet.getString("code");
                      }


1990-02-15 is 1973 and not February 15th 1990.

A useful debugging approach in those situations is to print the entire SQL statement prior to executing it.

A good approach would be to use a PreparedStatement:

PreparedStatement stmt = con.prepareStatement("select code from sportman where start = ?");
stmt.setDate(1, java.sql.Date.valueOf("1990-02-15");
resultSet = stmt.executeQuery();


Are you sure that's your actual code? You should be getting a compilation error from the missing parenthesis to your executeQuery() call. Also, 1990-02-15 is not a String. Is that error what you meant by "but resultset is empty"?


You are not telling us which DBMS you are using, but if you are using Oracle, that you probably need to cut off the time part that is part of an Oracle DATE column:

PreparedStatement stmt = con.prepareStatement("select code from sportman where trunc(start) = ?");
stmt.setDate(1, java.sql.Date.valueOf("1990-02-15");
resultSet = stmt.executeQuery();


resultSet = statement.executeQuery("select code from sportman "
                                + " where date ='1990-02-15'");

This works.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号