Select on the bank using "like"

1

I'm trying to make a select in the mysql database, but I'd like to use like , which should get the value of a java variable. How can I make 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();
    }
}
    
asked by anonymous 21.11.2017 / 11:45

2 answers

1

Your query is wrong. The correct would be:

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

Note: The signature of your method is missing the type of the userClient parameter

public void returInfoClient(TipoDoObjeto userClient) {
    
21.11.2017 / 12:42
0

In line 12 you pass the String that will be the search term concatenated with 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 userClient directly into the String sql, as R.Santos suggested, you can open a loophole for SQL Injection. You can see more about SQL Injection here .

    
21.11.2017 / 12:46