Create query with LIKE parameterized? (JAVA / UcanAccess)

1

Good! I come here with a small question: How exactly could a query be written using a Like and be parameterized? I'm using UcanAccess with JAVA.

I have a window in my program that requires the use of Like. Try first by writing it "normal" in this way, but it was not what I was looking for:

SELECT Diagnostico FROM Historial WHERE CedulaP LIKE ? ORDER BY Fecha ASC

I needed to insert the percentage character (%) so that it would work as I was looking for ... so what I did is write the following:

SELECT Diagnostico FROM Historial WHERE CedulaP LIKE CONCAT('%',?,'%') ORDER BY Fecha ASC

The query works well, but I do not know why I got doubts that doing it this way is safe, or not (because of the topic of the SQL injection ). This code that I wrote is where I prepare the PreparedStatement to execute the query:

public ResultSet SelectQuery(String[] values, String query) throws SQLException {
    PreparedStatement stmt = conn.prepareStatement(query);
    ResultSet rs;
    for(int i = 0; i<values.length; i++){
        stmt.setString(i + 1, values[i]);
    }
    rs = stmt.executeQuery();
    return rs;
}

Is it safe to consult the way you wrote it?

    
asked by TwoDent 28.10.2016 в 16:19
source

1 answer

1

If it is safe, since you can not do a subquery within a string (which is what you did) because the entire statement would be leaked, do not worry about the SQL injection problem would be if you did the following.

String variable ="(DELETE FROM Historial)as Hecho";
String query = "SELECT Diagnostico FROM Historial WHERE CedulaP LIKE CONCAT('%',"+varible+",'%') ORDER BY Fecha ASC";

With the preparedStatement as you have it, simply by concatenating it would happen like this

String query = "SELECT Diagnostico FROM Historial WHERE CedulaP LIKE CONCAT('%','(DELETE FROM Historial)as Hecho','%') ORDER BY Fecha ASC";

Something like that.

Greetings.

    
answered by 28.10.2016 / 16:35
source