2014-12-05 91 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