这是代码
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 +"\");");
答案 0 :(得分:1)
哦,我的。
看看这是否更好:
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();
我无法理解你为什么要编写那个代码来解析DateFormat诞生时的日期字符串。我当然希望您的birth_dt
列在数据库中的类型为Date。其他任何事都是完全愚蠢的。
答案 1 :(得分:0)
在您的代码中,您使用java.util.Date还是java.sql.Date?
在MySQL(或其他数据库)中插入Java日期的最佳方法是使用PreparedStatement和java.sql.Date类:
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();