【问题标题】:Java Timestamp to MySQL TimestampJava 时间戳到 MySQL 时间戳
【发布时间】:2015-04-25 11:36:48
【问题描述】:

我有这个代码,但它不工作。我有错误消息:

“com.mysql.jdbc.MysqlDataTruncation:数据截断:不正确的日期时间值:'' for column 'Datum_zalozeni' at row 1”

  pstmt = conn.prepareStatement(INSERT);
                Timestamp ts = u.getDatum_zalozeni();
                System.out.println(ts);
                pstmt.setTimestamp(1, ts);
                pstmt.setInt(2, u.getId_klient());
                pstmt.executeUpdate();

我的数据库是:

CREATE TABLE Ucet
(
  Id_Uctu Int NOT NULL auto_increment primary key,
  Datum_zalozeni Timestamp NOT NULL,
  Id_klient Int NOT NULL
)
;

哪里出错了?我认为代码是正确的。

【问题讨论】:

  • 您能否将值发布到“INSERT”变量中?
  • private static String INSERT = "插入 Ucet 值 (null,?,?)";当您手动插入时间戳时,它正在工作。

标签: java mysql timestamp


【解决方案1】:

我有一个生成系统时间戳的代码。它用 0 代替 979。看看吧。

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimestampTest
{
public static void main(String[] args)
{
    try
    {
        System.out.println("System Date: " + generateTimestamp("yyyy-MM-dd HH:mm:ss"));
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

public static Timestamp generateTimestamp(String format)
{
    Timestamp timestamp = null;

    try
    {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);

        Date date = dateFormat.parse(generateDate(format));

        timestamp = new Timestamp(date.getTime());
    }
    catch (ParseException e)
    {
        e.printStackTrace();
    }

    return timestamp;
}

public static String generateDate(String format)
{
    Date date = Calendar.getInstance().getTime();

    DateFormat dateFormat = new SimpleDateFormat(format);

    return (dateFormat.format(date));
}
}

【讨论】:

  • 它正在工作。太感谢了。但我不知道,为什么它不起作用,因为我手动使用:“INSERT INTO ucetnidb.Ucet values(null,'2015-03-31 14:24:25.979',1);”这是工作。
【解决方案2】:

MySQL 通常接受格式为“2013-12-06 14:24:34”的时间戳。如果您分享您尝试插入数据库的确切值,将会很有帮助。

Timestamp ts = u.getDatum_zalozeni();
System.out.println(ts);
pstmt.setTimestamp(1, ts);

什么是ts?

【讨论】:

  • 这是ts: 2015-04-25 16:17:22.979
  • 我们可以把 ts 中的 979 去掉,保留到 2015-04-25 16:17:22 吗?我是说导致它的 MysqlDataTruncation 错误
  • 但是我怎样才能删除 979?这是时间戳格式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 2015-02-07
  • 2012-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多