How to put simple apostrophes and concatenate with a string?

Asked

Viewed 378 times

1

I have a question, I want to be able to concatenate a String, so that it is interpreted with simple apostrophes between it.

For example, SQL would look like this:

SELECT IDALUNO, NOME, DATANASCIMENTO FROM ALUNO WHERE DATANASCIMENTO BETWEEN '07/03/1997' AND '10/03/2018';

What I want is that instead of the dates '07/03/1997' AND '10/03/2018' I can put two variables of the string type.

Example:

SELECT IDALUNO, NOME, DATANASCIMENTO FROM ALUNO WHERE DATANASCIMENTO BETWEEN 'dataInicial' AND 'dataFinal';

2 answers

4

Use PreparedStatment and ? for 'variables' as in:

Date dataInicial = ...;             // java.sql.Date
Date dataFinal = ...;
String query = "SELECT IDALUNO, NOME, DATANASCIMENTO "
    + "FROM ALUNO WHERE DATANASCIMENTO BETWEEN ? AND ?";
try (PreparedStatement stmt = connection.prepareStatement(query)) {
    stmt.setDate(1, dataInicial);
    stmt.setDate(2, dataFinal);
    try (ResultSet rset = stmt.executeQuery()) {
        ...
    }
}

This way there is no dependency on how the date is displayed/formatted.

Note that the class Date is of the package java.sql and not that of java.util!

  • From Java 8 an alternative to the use of java.sql.Date is to match package objects java.time (e. g., LocalDate) with stmt.setObject. For more details see: https://stackoverflow.com/a/31238011/664577

1


Well, you didn’t put much there, so if I understood correctly, all you have to do would be something like:

"SELECT IDALUNO, NOME, DATANASCIMENTO FROM ALUNO WHERE DATANASCIMENTO BETWEEN '" + dataInicial + "' AND '" + dataFinal + "'";
  • This Strings concatenation strategy is subject to attacks from SQL Injection, unless you can guarantee dataInicial and dataFinal have been properly sanitized recommend the use of PreparedStatementin accordance with the response of Carlos

Browser other questions tagged

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