从字符串转换为TimeStamp数据类型 [英] conversion from string to TimeStamp data type

查看:2652
本文介绍了从字符串转换为TimeStamp数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将此转换:17:26:54转换为TimeStamp数据类型。我需要将它输入数据库。我该怎么做呢?
我有一个字符串变量
中的数据我正在使用java。
我正在从另一个源中提取这些数据,我需要将其推送到数据库,其中时间戳的列被定义为TimeStamp类型。我正在使用JDBC将数据从java程序推送到MySQL。
所以我需要一个解决方案将字符串:17:26:54转换为timeStamp数据类型,以便可以输入数据库而不会抛出sql异常错误。

i want to convert this : 17:26:54 to a TimeStamp data type. I need to enter it into a database. How do i do this? i have the data in a string variable i'm using java. I'm extracting this data from another source and i need to push it into a databse, in which the column for time stamp is defined to be of the type TimeStamp. I'm using JDBC to push data from the java program to MySQL. So i need a solution to convert the string : 17:26:54 to the timeStamp datatype so that it can be entered into the database without throwing an sql exception error.

编辑:我不需要timeStamp的日期部分,因为我不会在计算中的任何地方使用它,也不能从生成时间信息的源中提取它。

edit: I do not need the date part of the timeStamp because i do not use it anywhere in my computations, and neither do I have the option of extracting it from the source which is generating the time information.

推荐答案

使用 PreparedStatement#setTime() PreparedStatement#setTimestamp()插入 java.sql.Time java.sql.Timestamp

转换字符串到日期或时间戳使用 SimpleDateFormat

To convert String to Date or Timestamp use SimpleDateFormat

示例代码:

 String time="12/07/2014 17:26:54";

 SimpleDateFormat format=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
 Date date=format.parse(time);

如果你尝试下面的示例代码,那么默认日期将是1970年1月1日

If you try below sample code then default date will be Jan 1, 1970

 String time="17:26:54";

 SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss");
 Date date=format.parse(time);

如何将Java日期转换为SQL日期?

How to convert Java date to SQL date?

 java.util.Date javaDate=new java.util.Date();
 java.sql.Date sqlDate=new java.sql.Date(javaDate.getTime());








如何插入它进入数据库时​​间戳数据类型?

How to insert it into database timestamp data type?

示例代码:

String time="17:26:54";

SimpleDateFormat format=new SimpleDateFormat("HH:mm:ss");
Date date=format.parse(time);

...

PreparedStatement stmt = conn
        .prepareStatement("insert into test(message,time) values(?,?)");
stmt.setString(1, "This is message");
stmt.setTimestamp(2, new java.sql.Timestamp(date.getTime()));
stmt.executeUpdate();

查找完整示例代码

这篇关于从字符串转换为TimeStamp数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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