Java Date - Insert into Database

Java Date - Insert into database

Granted, PreparedStatement will make your code better, but to answer your question you need to tell the DBMS the format of your string representation of the Date. In Oracle (you don't name your database vendor) a string date is converted to Date using the TO_DATE() function:

INSERT INTO TABLE_NAME(
date_column
)values(
TO_DATE('06/06/2006', 'mm/dd/yyyy')
)

Insert Date in string format into a database having field type of Date

You need to use a java.sql.Date when inserting in database. Try the following :

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date fd = formatter.parse(from_date);
java.sql.Date sqlDate = new java.sql.Date(fd.getTime());
select1.setDate(1, sqlDate);

Insert datetime to database

You need to use java.sql.Timestamp instead of java.sql.Date.

The java.sql.Timestamp has the date and the time. Have a look at the docs.

Also, it is important that the column of the table is of type Timestamp.

How to insert Date into mysql?

Use a PreparedStatement. It's almost never correct to use string concatenation to create SQL code to send through JDBC.

PreparedStatement ps = connection.prepareStatement("insert into device_sales_details values(?)");
ps.setDate(1, sqlDate);
int i = ps.executeUpdate();

More about not using string concatenation here: http://bobby-tables.com


Separately, it's generally best to specify the columns when doing an insert, e.g.: insert into device_sales_details (columnName) values (?)

Inserting date in mysql databate using java

Your exception comes from this line:

java.sql.Date dob = (java.sql.Date) new SimpleDateFormat("yyyy/MM/dd").parse(sDate1);

since parse will return a java.util.Date, not a java.sql.Date. You cannot cast to a java.sql.Date since the two are not related.

You can get rid of it by instansiating a java.sql.Date with

java.sql.Date dob = new java.sql.Date(new SimpleDateFormat("yyyy/MM/dd")
.parse(sDate1)
.getTime());

but I'd recommend you avoid using java.util.Date, and instead use:

  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.parse(sDate1, formatter);
java.sql.Date dob = java.sql.Date.valueOf(localDate);

Insert current date and time using java.util.Date object in MySQL

To insert a date and a time, you need to use setTimestamp instead of setDate and the datatype of your database column must be DATETIME (or TIMESTAMP).

Quoting setDate Javadoc:

The driver converts this to an SQL DATE value when it sends it to the database.

and quoting MySQL documentation:

The DATE type is used for values with a date part but no time part.

Working code:

ps.setTimestamp(1, new java.sql.Timestamp(new Date().getTime()));

How to insert a date in the database in JavaEE?

Use this:

ps.setDate(1,new java.sql.Date(studentBean.getTargetdate().getTime())); 


Related Topics



Leave a reply



Submit