简体   繁体   中英

PreparedStatement

I am using PreparedStatement's setString method to set values for the start and end dates in a sql query.

String sql = "..... " AND tableA.time BETWEEN ? " +
                    " AND ?";

PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, startDate);
st.setString(2, endDate);

The values however are not being set. I understand that normally there is an equals sign: "tableA.member_id = ?" +"

How do I than call setString method when I am using a 'Between' operator in the sql statement? Hope someone can advise. Thank you.

See http://docs.oracle.com/cd/B28359_01/server.111/b28286/conditions011.htm

"BETWEEN" can be used with datetime data types. However, if tableA.time is a datetime field of some kind (Timestamp, etc.), using st.setString(...) won't work. You need to use setDate(dt) or setTimestamp(ts) instead. See Using setDate in PreparedStatement for more info.

Use setDate .

Is your startDate and endDate a java.util.Date object?

If it is, you can use this code.

st.setDate(1, new java.sql.Date(startDate.getTime()));
st.setDate(2, new java.sql.Date(endDate.getTime()));

If it is not. Convert that first ro java.util.Date object.

BETWEEN expects its arguments to have a type that is compatible with the column being tested. Giving it string arguments for a date column won't work.

You could add a function to the SQL in order to convert the string to a date (I don't know what database you're using, this example uses Oracle's to_date function):

from tableA.time BETWEEN to_date(?, 'yyyy/mm/dd') AND to_date(?, 'yyyy/mm/dd')

Alternatively you could leave the SQL alone and use setDate on the PreparedStatement, like:

setDate(1, new SimpleDateFormat("yyyy/MM/dd").parse(startDate));

This second way is more usual, it has the advantage of avoiding having to add a date-conversion function (that may be non-standard) to your SQL.

But you would have to do the conversion on one side or the other. The database's SQL parser won't convert it for you. If the database took responsibility for the conversion and there was a mistake it could introduce data errors silently, the less error-prone alternative is for the application developer to tell the database how the date string should be converted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM