problem in adding java date in MySQL?
here is the code
String DateOfBirth[]=strDOB.split("/");
Date dateOfBirth = new Date();
dateOfBirth.setYear(Integer.parseInt(DateOfBirth[2].trim()));
dateOfBirth.setMonth(Integer.parseInt(DateOfBirth[1].trim()));
dateOfBirth.setDate(Integer.parseInt(DateOfBirth[0].trim()));
java.text.SimpleDateFormat DateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
strDOB = DateFormat.format(dateOfBirth);
DBProcess.QueryExecuter("INSERT INTO patients(patient_id,first_name,last_name,middle_name,birth_dt) VALUES (\""+Double.parseDouble(strPatientID.trim())+"\",\""+strFirstname+"\",\""+strLastname+"\",\""+strMiddlename开发者_运维知识库+"\",\""+strDOB +"\");");
Oh, my.
See if this is better:
private static final String INSERT_SQL = "insert into patients(patient_id, first_name, last_name, middle_name, birth_dt) values(?, ?, ?, ?, ?)";
DateFormat inputFormatter = new SimpleDateFormat("dd/MM/yy");
Date dob = inputFormatter.parse(strDOB);
PreparedStatement ps = connection.prepareStatement(INSERT_SQL);
// bind your values here.
int numRowsAffected = ps.executeUpdate();
I can't understand why you'd write that code to parse a date string when DateFormat was born to do it. And I certainly hope that your birth_dt
column is of type Date in your database. Anything else is utterly foolish.
In your code, do you use java.util.Date or java.sql.Date ?
The best way to insert a Java date in MySQL (or other DB) is to use the PreparedStatement, and the java.sql.Date class :
java.sql.Date theDate = new Date(longTime);
PreparedStatement stmt = conn.prepareStatement("INSERT INTO table(id,date) VALUES (?,?)");
stmt.setInt(1, 123);
stmt.setDate(2, theDate);
stmt.execute();
精彩评论