问题
I want to update the string date into MySQL database using prepared statement. I have tried a lot and always got error java.util.Date cannot parse into java.sql.Date
or vise versa. I didn't import anything here. Please import according to your answer.
public class Date1
{
public static void main(String args[])
{
String source="2008/4/5";
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date d=(Date) format.parse(source);
Class.forName("com.mysql.jdbc.Driver");
Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/employee", "root", "root");
PreparedStatement ps=con.prepareStatement("insert into ankur1 values(?)");
ps.setDate(1,(java.sql.Date) d);
ps.executUpdate();
}
}
回答1:
Write this
java.sql.Date d= new java.sql.Date(format.parse(source).getTime());
instead of this:
java.sql.Date d=(Date) format.parse(source);
Because you cannot just cast java.util.Date
to its subtype java.sql.Date
. You have to convert it. Do also note that your format string doesn't match your actual date format, as Bill the Lizard commented.
回答2:
java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime());
pstmt.setTimestamp(1, date);
Try this it may work.. Thanks
回答3:
here is another simpler way to solve this:
preparedStatement = connect.prepareStatement("INSERT INTO test.TABLENAME VALUES (default, STR_TO_DATE( ?, '%m/%d/%Y'), STR_TO_DATE(?, '%l:%i %p'),?,?,?,?,?)");
Or, you can replace the "?" with real data.
This is how I insert date and time to mySQL, just figured it out.
We can adjust the kinds of parameters to meet our data's format, it's easy and clean.
来源:https://stackoverflow.com/questions/12916262/inserting-date-into-mysql-database-using-a-preparedstatement