Java日期到SQL日期 [英] Java date to sql date

查看:216
本文介绍了Java日期到SQL日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将Java中的特定日期存储到数据库中? (不仅是今天的日期,而且还有用户想要指定的一些日期)

How can I store a specific date from java to my database? (Not only the date today, but also some dates that the user wants to specifiy)

try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");       
        Date date = dateFormat.parse(tf.getText());
        String d = dateFormat.format(date); 

        String str = "insert into tableName(tDate) values (?)";
                con = mysqlConnection.dbConnector();
                prs = con.prepareStatement(str);
                prs.setDate(1, // dont know what to put here);

                int rsUpdate = prs.executeUpdate();
                con.close();
                prs.close();
    } catch(ParseException exx) {
                System.err.println(exx);

推荐答案

使用

prs.setDate( 1, new java.sql.Date( date.getTime() ) );

假定类型java.sql.Datejava.sql.Timestamp分别用于设置日期和时间戳字段.阅读他们的文档,了解它们之间以及与java.util.Date之间的区别.

The types java.sql.Date and java.sql.Timestamp are suppoed to be used to set date and timestamp fields, respectively. Read their documentation for the differences between them and between them and java.util.Date.

通常您会从用户那里获得一个Java日期(java.util.Date).您可以使用getTime()将其转换为自纪元以来的毫秒数,然后再转换回java.sql.Datejava.sql.Timestamp,如我所示.

You usually get a java date (java.util.Date) from the user. You convert it to milliseconds since the epoch using getTime(), and then convert back to a java.sql.Date or java.sql.Timestamp as I have shown.

这篇关于Java日期到SQL日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆