How to insert a string date to a mysql database date field
I'm trying to insert a date String from my Java program to one of my MySQL database fields that has a date type.
package events;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Date;
/**
*
* @author mewq
*/
public class ConDb {
public static void main(String[] args){
String description = null;
try{
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/tangkilikan", "user=root", "password=tangkilik");
Statement stat = (State开发者_运维知识库ment) conn.createStatement();
String eventName = "Imba meeting";
String Address = "Zamora, Cabarroguis, Quirino";
Date date = '2011-09-09';
String description = "meeting";
String insert = "insert into events values ('" + eventName + "', '" + Address + "', ' + date + ', '" + description + "')";
stat.executeUpdate(insert);
} catch(Exception e) {
}
}
}
Date date = '2011-09-09';
won't compile. The correct approach to inserting date into a database table with a date type is to use a PreparedStatement.
String dateString = "2011-09-09";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = formatter.parse(dateString);
String insert = "insert into events values (?, ? , ? , ?)";
PreparedStatement ps = conn.prepareStatment(insert);
ps.setString(1, eventName);
ps.setString(2, Address);
ps.setDate(3, myDate);
ps.setString(4, description);
ps.executeUpdate();
Try to use a SimpleDateFormat
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date date = (Date)formatter.parse("05/15/11");
and use the resulting Date for the insert.
As a matter of convention, your variable/field/member names shouldn't start with a capital letter, so Address
should actually be address
.
As for your question, there's a problem with the creation of the insert
String in the code you posted; you're not ending the string with a double quote (") before trying to concatenate your date
field, so you're not going to end up with the String you're expecting. Try the following instead:
String insert = "insert into events values ('" + eventName + "', '" + Address + "', '" + date + "', '" + description + "')";
mysql date time format is '2013-01-01 01:00:00' OR YYYY-MM-DD HH:MM:SS make sure you have that in quotes or ticks..
-> try casting that date object to a string.
best I can do without more info.
精彩评论