Java + mySQL:将日期读为字符串

时间:2012-09-27 12:45:34

标签: java mysql datetime

我尝试读出一张表并将其写入csv文件。

while (rs2.next())
{
    Enumeration<String> en = sqlfields.keys();
    while (en.hasMoreElements())
    {
        String field = en.nextElement();
        String value = rs2.getString(field);
        bw.write(Kapseln + value + Kapseln + Trennzeichen);
    }

    bw.newLine();
    cur++;
}

但是如果字段是type:DateTime,我收到此错误消息:

java.sql.SQLException: Cannot convert value 
'0000-00-00 00:00:00' from column 12 to TIMESTAMP.

为什么Java会尝试转换为时间戳?

我喜欢将值设为String =&gt; rs2.getString(field)

2 个答案:

答案 0 :(得分:3)

设置

zeroDateTimeBehavior="convertToNull"

在JDBC连接属性中。参考:http://dev.mysql.com/doc/refman/5.1/en/connector-j-reference-configuration-properties.html

编辑会使您的连接字符串如下所示:

jdbc:mysql://yourserver:3306/yourdatabase?zeroDateTimeBehavior=convertToNull

答案 1 :(得分:0)

以下代码正常运行。用这个检查你的代码...... emp表的第四个字段是jDate,它是一个DateTime数据类型。

        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","test");

        System.out.println("Connection is : " + con);
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("select * from emp");

        //stmt = con.createStatement();

        while(rs.next()) {
            String value = rs.getString(4);
            System.out.println(value);
        }
        System.out.println("Connection is : " + con);
        con.close();