[英]How to insert a value into a type date column of database?
How to save the value of a variable that is as a date to the database. 如何将变量的值保存为数据库的日期。
My String is as following 我的字符串如下
Java Java的
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
SimpleDateFormat parseFormatter = new SimpleDateFormat("yyyy-MM-dd");
//SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss+hh:mm");
Date date = parseFormatter.parse(mydate);
String formattedDate = formatter.format(date);
System.out.println("Date"+formattedDate);
return formattedDate; <<need to save its value to database lets say its value is 2013-03-19
I need to save it into a column of table that its type is date. 我需要将其保存到类型为日期的表的列中。
Database 数据库
Name Type
Date date
I suppose I need to convert the string to date but how? 我想我需要将字符串转换为日期,但是如何?
ps.setDate(????)
if mydate is a string in yyyy-MM-dd format then you can do the following 如果mydate是yyyy-MM-dd格式的字符串,则可以执行以下操作
PreparedStatement ps = conn.prepareStatement("insert into t1 (date) values (?)");
ps.setDate(1, java.sql.Date.valueOf(mydate));
ps.executeUpdate();
Use the STR_TO_DATE function in MySql 在MySql中使用STR_TO_DATE函数
EDIT 编辑
eg 例如
INSERT INTO table (dateCol1, col2 ..)
VALUES (STR_TO_DATE('May 1, 2013','%M %d,%Y'), col2value, ...)
MySQL understands dates. MySQL可以理解日期。 Assuming you are using a
PreparedStatement
you can just use standard JDBC stmt.setDate(n,date)
where n
is the parameter index and date
is a Java variable of type date. 假设您正在使用
PreparedStatement
,则可以仅使用标准JDBC stmt.setDate(n,date)
,其中n
是参数索引,而date
是date类型的Java变量。
No need to do any string conversions. 无需进行任何字符串转换。
I suppose I need to convert the string to date but how?
我想我需要将字符串转换为日期,但是如何?
If you want to convert String
into Date
, suppose your String
is 2013-03-19
如果要将
String
转换为Date
,请假设您的String
为2013-03-19
String yourString = "2013-03-19";
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(yourString);
Here your String
is converted into the Date
object, but if you need to set this particular date into another date object then this is not possible in this way yourDateObj.setDate(date)
because there is no any such direct method in Date class which will take date as an argument. 在这里,您的
String
会转换为Date
对象,但是如果您需要将此特定日期设置为另一个date对象,则无法通过yourDateObj.setDate(date)
这样yourDateObj.setDate(date)
因为Date类中没有任何此类直接方法,以日期为参数。
to set a particular date you can use Calendar like 要设置特定日期,您可以使用“日历”
Calendar yourDate = new GregorianCalendar();
yourDate.setTime(date);
Other wise you can do this way also with Date(int year, int month, int date)
but it is deprecated now. 否则,您也可以使用
Date(int year, int month, int date)
但是现在不建议使用。
Or If you wish to insert String
into Date
column of mysql
then #function_str-to-date , I agree with Ed Heal answer 或者,如果您希望将
String
插入mysql
Date
列,则#function_str-to-date ,我同意Ed Heal的回答
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.