Search code examples
javasqlitejdbcprepared-statementwhere-clause

How to include parameters in Prepared Select Statement in Java?


I'm trying to run a simple select statement in my program. Insert and Create work just fine. But my select query doesn't get any results. If I run the statement directly in the sqlite console I get results, so I image I must have an error in my prepared statement.

I have my Queries in another Java-Class and access them directly as static variables (and those work for create and insert as well)

Here what I have:

Queries.java

[...]
    public static final String SELECT_TOPIC_BY_NAME_AND_DESCRIPTION =
            "SELECT * FROM topics WHERE name=? AND description=?";
[...]

Connector.java

[...]
for (Topic topic : scan.getTopicList()) {
            PreparedStatement topicStatement = connection.prepareStatement(Queries.SELECT_TOPIC_BY_NAME_AND_DESCRIPTION);
            topicStatement.setString(1, topic.getName());
            topicStatement.setString(2, topic.getDescription());
            ResultSet topic_resultSet = topicStatement.executeQuery();
            if (topic_resultSet.getFetchSize() == 1) {
                [...]
            }
            else{
                System.out.println("Couldn't Find Topic: {name: "+topic.getName()+"; description: "+topic.getDescription()+"}");
            }
        }
[...]

The Topics are the same one I inserted before, so the name and description couldn't have changed. If I run it it gives me the following output:

Couldn't Find Topic: {name: Money; description: Alles was mit Money zu tun hat}

Couldn't Find Topic: {name: Banking; description: Alles was mit Banking zu tun hat}

Couldn't Find Topic: {name: Money; description: Alles was mit Money zu tun hat}

Couldn't Find Topic: {name: Banking; description: Alles was mit Banking zu tun hat}

But if run the select statement I want in sqlite it gives me the correct result:

main> SELECT * FROM topics WHERE name='Money' AND description='Alles was mit Money zu tun hat'

1,Money,Alles was mit Money zu tun hat
3,Money,Alles was mit Money zu tun hat

I'd appreciate any help


Solution

  • Your if statement is not correct. This

    if (topic_resultSet.getFetchSize() == 1) {
    

    does not return a row count. Nor does it have anything to do with the query being matched. You wanted

    if (topic_resultSet.next()) {
    

    to check for a row.