#What is the correct way to add a LIKE query ?

1 messages · Page 1 of 1 (latest)

static muskBOT
#

<@&987246584574140416> please have a look, thanks.

bold fjord
#

string literals must be escaped

#

like '%?%'

errant lagoon
#

I have tried doing it that way, doesn't work.

#

The ? needs to be outside the " or ' for it to work in preparedStatement.setString(1, filter);

queen bloom
#

So WHERE naslov LIKE ?

#

And then

#

.setString("%" + filter + "%")

errant lagoon
#

preparedStatement.setString(1, "%" + filter + "%"); -- i have done it like this and it doesn't work.

SQLSyntaxErrorException: 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

queen bloom
#

"SELECT * FROM Projekt WHERE naslov LIKE ?"

errant lagoon
#

public static ArrayList<Projekt> preberiIzBazeProjekteZFiltrom(String filter) {
ArrayList<Projekt> seznamP = new ArrayList<Projekt>();
try (Connection povezava = DriverManager.getConnection(povezavaBaza, upIme, geslo)) {
String SQLProjekti = "SELECT * FROM Projekt WHERE naslov LIKE ?";
PreparedStatement preparedStatement = povezava.prepareStatement(SQLProjekti);
preparedStatement.setString(1, "%" + filter + "%");
ResultSet podatki = preparedStatement.executeQuery(SQLProjekti);;

            while (podatki.next()) {
                seznamP.add(new Projekt(podatki.getInt("idProjekta"), podatki.getString("naslov"), podatki.getString("opis"), podatki.getString("deadline"), podatki.getString("naloge")));
            }

        } catch (Exception e) {
            System.out.println("Napaka pri MYSQL (filter):" + e);
        }
        return seznamP;
    }
queen bloom
#

that should be fine

#

and you say you are getting an exception with that code?

#

does mysql have like?

#

hmm yeah it does

#

curious

errant lagoon
#

Yeah i've look over forums tried everything they said worked for them and nothing. Getting the same error

#

I have a function that imports data into the database with the same ? and it works.

#

so i am guessing it has something to do on how to do the LIKE query in java

queen bloom
#

err

#

unfortunately i don't have mysql ready to test

#

nothing seems wrong with your code though

#

(aside from using DriverManager - use a DataSource!)

dawn gale
queen bloom
#

oh that explains it

#

yeah i missed that

#
                PreparedStatement preparedStatement = povezava.prepareStatement(SQLProjekti);
                preparedStatement.setString(1, "%" + filter + "%");
                ResultSet podatki = preparedStatement.executeQuery(SQLProjekti);;
#

instead of this

#
                PreparedStatement preparedStatement = povezava.prepareStatement(SQLProjekti);
                preparedStatement.setString(1, "%" + filter + "%");
                ResultSet podatki = preparedStatement.executeQuery();;
#

this