Date and Time search help

0

Good Morning

I'm doing a date search on android and am having trouble checking the time.It says it gave the syntax error about the time, and another one when I get the date the time is showing less than 3 hours. Can someone help me? follow the code the format of the time I get on the bank is this: 2016-11-23 16: 34: 37,000

public String nomeTabela()  {
    String Pesquisa = "";
    ConexaoDao conexao = new ConexaoDao();
    ObjetoConexao objConexao = new ObjetoConexao();
    objConexao.db_connect_string = "flexvale.hopto.org:1433";
    objConexao.db_name = "FlexPortaCom";
    objConexao.db_userid = "sa";
    objConexao.db_password = "flextelecom";
    Connection conn = conexao.dbConnect(objConexao);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    String currentDateandTime = sdf.format(new Date () );
    System.out.println(currentDateandTime);

    if (conn == null) {

        Pesquisa = "Não foi possivel se conectar ao banco de dados";

    } else



    if (conn != null) try {


        Statement statement = conn.createStatement();

        String queryString =  " Select SUM(DIFERENÇA)as somaMes from TOTALIZADOR WHERE  NID = 252 and DATAHORA  >= "+currentDateandTime+" and DATAHORA = "+currentDateandTime+" ";
        ResultSet rs;



        rs = statement.executeQuery(queryString);

        if (rs.next()) {

            Pesquisa = rs.getString("somaMes");

        }
    } catch (SQLException e) {
        Pesquisa = e.getMessage();


    }
    return Pesquisa ;




}
    
asked by anonymous 06.12.2016 / 12:19

1 answer

1

Although it is possible to execute an SQL query using concatenation of text, do not do it, because it is putting your system at risk when allowing SQL injection.

Use a PreparedStatement and pass the date parameters using the < a href="https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#setDate(int,%20java.sql.Date)"> setDate() .

Example :

private static java.sql.Date getCurrentDate() {
    java.util.Date today = new java.util.Date();
    return new java.sql.Date(today.getTime());
}

public String nomeTabela()  {

    ...

    String insertTableSQL = "INSERT INTO DBUSER"
        + "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
        + "(?,?,?,?)";
    preparedStatement = dbConnection.prepareStatement(insertTableSQL);    
    preparedStatement.setDate(4, getCurrentDate());

    ...

}

Note: If you want to concatenate a literal date, the first step is to put quotation marks before and after, after all there is a space between the date and time. Of all the banks I know of, some accept a text literal and make the conversion implicit for a date. However, in this case you will probably need to use a function to explicitly convert the string to date / time .

    
08.12.2016 / 03:57