How to put simple apostrophes and concatenate with a string?

2

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 dates '07/03/1997' AND '10/03/2018' I can put two variables of type string.

Example:

SELECT IDALUNO, NOME, DATANASCIMENTO FROM ALUNO WHERE DATANASCIMENTO BETWEEN 'dataInicial' AND 'dataFinal';
    
asked by anonymous 18.03.2018 / 20:17

2 answers

1

Well, you did not put much there, 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 + "'";
    
18.03.2018 / 20:37
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 presented / formatted.

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

    
19.03.2018 / 15:45