Home  >  Q&A  >  body text

如何比较java中的Date与mysql中datetime类型的字段?

现在mysql数据库db有一张表test(id bigint,createTime datetime),部分表数据如下:

id createTime
1 2017-01-02 10:34:33
2 2017-01-05 11:35:31
3 2017-01-07 13:20:01
4 2017-01-13 10:06:33
5 2017-01-15 11:22:53
6 2017-01-20 10:34:33
7 2017-01-25 10:46:25

现在要通过java代码拼接sql字符串的形式查出所有创建时间在2017-01-15 00:00:00之后的数据。

限定 : 通过以下两种方式查询

String sql = "select id,createTime from db.test where createTime > " + javaCreateTime
String sql = "select id,createTime from db.test where createTime > ?"

请问 : 第一种方式的javaCreateTime应该怎么传?第二种预编译的方式参数又应该怎么传?


从网上找到解决的办法了:

String sql = "select id,createTime from db.test where createTime > '2017-01-15 00:00:00' "
String sql = "select id,createTime from db.test where createTime >  ? ";
PreparedStatement preStat = connection.prepareStatement(sql);

preStat.setString(1, '2017-01-15 00:00:00');
ResultSet rs = preStat.executeQuery();

以上两种方式都是直接传入字符串,而且都是yyyy-MM-dd HH:mm:ss。请问为什么可以达到目的?
mysql会自动将字符串转化为datetime?。
其底层运行机制到底是什么原因呢?


ringa_leeringa_lee2743 days ago650

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-04-18 10:56:42

    Will mysql automatically convert strings to datetime?

    It depends on their own datatype是不是datetime

    when you add them to the table

    Or maybe they are mysql的column可能已經set成datetime

    You can call desc test;to view

    Also 2017-01-15 00:00:00 本身的格式已經是 datetime.

    reply
    0
  • Cancelreply