2014-12-05 49 views
0

我是新來的Java GUI在Java中處理日期

我有一個簡單的數據輸入表格,保存到mySQL。我定義的文本框是dateOfBirth。

在mySQL中,dateOfBirth列的類型是DATE。

當我試圖保存我的記錄時,我得到不兼容的轉換。我該如何處理?日期字段是DOR和DOB。

我試圖定義的格式:

DateFormat df= new SimpleDateFormat("dd/MM/yyyy"); 

和也改變重新定義了var DOR或DOB作爲字符串:

String DOB = new String(); 

然後當插入到數據庫中,格式化這樣的變種: df.format(DOB)

我仍然收到錯誤:「錯誤:無法格式化給定的對象作爲日期」。該怎麼辦?

String query = "INSERT INTO members (MemberID,FamilyName,BaptismName,DateOfRegistration,DateOfBirth,FatherName,MotherName,gender,MemberType,Address,Residence,City,CreatedBy)" 
    +"VALUES('"+memberID+"','"+familyName+"','"+baptismName+"','"+DOR+"','"+DOB+"','"+fatherName+"','"+motherName+"','"+gender+"','"+memberType+"','"+address+"','"+residence+"','"+city+"','"+operator+"')"; 

    con.UpDate(query); 
+0

因爲DOB似乎是一個字符串,而不是一個日期,它不是做與格式 – 2014-12-05 13:04:25

+2

請閱讀有關的PreparedStatement什麼。不要自己逃避查詢參數。爲什麼你將日期建模爲字符串? – duffymo 2014-12-05 13:11:43

+0

MySQL日期格式是yyyy-MM-dd HH:mm:ss – Sal 2014-12-05 13:12:37

回答

1

首先,我不會使用該查詢插入。你應該使用一個準備好的聲明。這對sql注入更安全。

PreparedStatement ps = 
    connection.prepareStatement("INSERT INTO members (MemberID,FamilyName,BaptismName,DateOfRegistration,DateOfBirth,FatherName,MotherName,gender,MemberType,Address,Residence,City,CreatedBy) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)"); 
ps.setString(1, memberID); //or the correct type if not String 
ps.setString(2, familyName); 
ps.setString(3,baptismName); 
DateFormat df= new SimpleDateFormat("dd/MM/yyyy"); //this the the format in which the user enters the date in the textbox. they have to input a string like 12/31/2014 
java.util.Date date=df.parse(DOB); //DateFormat class has a method called parse which returns a java.util.Date object 
ps.setDate(4, new java.sql.Date(date.getTime())); 
//PreparedStatement class method setDate takes 2 parameters 
//first is the index of the parameter in the prepared statement, and the second 
//is java.sql.Date object. 
//use constructor of java.sql.Date which takes a long parameter to create this object 
//java.util.Date getTime() method returns a long value representing the date object 
//so basically you convert string DOB to java.Util.Date, 
//then convert java.Util.Date object to java.sql.Date needed by prepared statement 

... 

ps.executeUpdate(); 
+0

謝謝@MihaiC,如何將在swing文本框中輸入的值(我假設它是一個默認字符串)賦值給DOB而不會出現錯誤? – Sylvester 2014-12-05 13:18:24

+0

@Sylvester如果DOB是字符串,只需從文本框中複製值DOB = textBox.getText();在將值設置爲準備好的語句之前,將其轉換爲java.sql.Date。該字符串必須以您用來轉換日期的相同格式輸入,因此在這種情況下,用戶必須編寫31/12/2014或該格式的任何日期。 – MihaiC 2014-12-05 13:40:48

+0

對不起,我無法理解日期格式。我曾與vb.net廣泛,但我似乎無法理解我必須做的多行代碼,只是爲了將一個字段保存到數據庫。我正在梳理網絡,但沒有看到,找到任何確切的東西。 – Sylvester 2014-12-05 13:49:26