2010-08-23 19 views
0

這裏是代碼在MySQL中添加java日期的問題?

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 +"\");"); 
+1

和...究竟是什麼問題?對錯誤的描述(以及預期的行爲)將非常有幫助。 – 2010-08-23 09:18:04

+0

搶常量字符串'INSERT INTO ....'的價值,並直接在MySQL客戶端執行它。它會失敗。然後讓它在該客戶端中工作並將更改應用到您的Java代碼。 – 2010-08-23 09:23:47

回答

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。還有什麼是完全愚蠢的。

0

在你的代碼,你用java.util.Date還是java.sql.Date?

插入在MySQL(或其他DB)一個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();