Select in the database using "like"

Asked

Viewed 156 times

1

I am trying to make a select in mysql database, but would like to use the like, that should receive the value of a java variable. How can I do this interaction?

public void returInfoClient(userClient) {

    Connection mConn = (new ConnectionFactory()).getConnection();

    String sql = "SELECT nameClient, userClient, descriptionClient, passwordClient, birtDate 
                  FROM Client 
                  WHERE userClient LIKE 'userClient%';" //quero que o userClient venha do parametro da função
                  + "values(?);";

    try {
        PreparedStatement stmt = mConn.prepareStatement(sql);
        stmt.setString(1, userClient); //quero usar o userClient do parametro da função para o like do select
        stmt.execute();
        stmt.close();
        System.out.println("retornando informações author");
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

2 answers

2


Your query is wrong. The correct one would be:

String sql = "SELECT nameClient, userClient, descriptionClient, passwordClient, birtDate FROM Client WHERE userClient LIKE '?%';"

Note: Your method signature is missing the userClient parameter type

public void returInfoClient(TipoDoObjeto userClient) {

1

On line 12 you pass String which will be the search term concatenated with the wildcard % of like

public void returInfoClient(userClient) {

    Connection mConn = (new ConnectionFactory()).getConnection();

    String sql = "SELECT nameClient, userClient, descriptionClient, passwordClient, birtDate  FROM Client  WHERE userClient LIKE ?";

    try {
        PreparedStatement stmt = mConn.prepareStatement(sql);
        stmt.setString(1,  userClient + "%"); 
        stmt.execute();
        stmt.close();
        System.out.println("retornando informações author");
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

If you put the userClient directly in String sql, as R.Santos suggested, can open a gap for SQL Injection. You can see more about SQL Injection here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.