Search code examples
javasqljtablejcomboboxsetstring

Java setString() can not find the?


I am quite new to programming but I am making a screen for a back office application. The goal of this application is that you can select the station name and when you press check status then all the statuses of the locker on that station are shown. But the problem that I am having is stat the setString isn’t working for some strange reason. I have tried almost everything also I have asked quite a lot of people if they could find the problem even people who work with java as their job , but even they couldn’t find it.

The only thing that I can see here is that the ? isn’t being recognized.

I first tried butting Amersfoort directly in to the sql code and it worked.

After a bit of testing I tried using a normal query without joins but it didn’t work.

After that I try to find a possible mistake in the rest of my code but I couldn’t find any.

So my question is what am I doing wrong here ?

(Small disclaimer I tried more than this but I think it is quite irrelevant)

A bit of explanation about the output screen:

Akkrum is what I was selecting during the testing but is irrelevant because at the moment I am not using it.

The code :

public void fetch() {

    try {
        databaseConnection();
        String select = stationSelect.getSelectedItem().toString();
        System.out.println(select);

        String sql = "SELECT l.id, s.station_id, locker_number, locker_code, occupied FROM lockers l JOIN stations s ON l.station_id = s.id WHERE name = ?"; 
        System.out.println(1+ ": "+ sql);

        pstmt  = connection.prepareStatement(sql);
        pstmt.setString(1, "Amersfoort");
        System.out.println(2+ ": " + sql);

        resultSet = pstmt.executeQuery(sql);
        System.out.println(3 + ": " + sql);

        Table.setModel(DbUtils.resultSetToTableModel(resultSet));

    } catch (Exception e) {
        System.out.println(e);
        JOptionPane.showMessageDialog(null, e);
    }
}

The output:

Akkrum

  1. SELECT l.id, s.station_id, locker_number, locker_code, occupied FROM lockers l JOIN stations s ON l.station_id = s.id WHERE name = ?

  2. SELECT l.id, s.station_id, locker_number, locker_code, occupied FROM lockers l JOIN stations s ON l.station_id = s.id WHERE name = ?

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1


Solution

  • resultSet = pstmt.executeQuery(sql);
    

    The error is there. executeQuery(String) takes a raw SQL query and executes it. Instead, you want to execute the prepared query, so you just need to call:

    resultSet = pstmt.executeQuery();