用Java处理日期
我不熟悉JavaGUI 我有一个保存到mySQL的简单数据输入表单。在我定义的文本框中有dateOfBirth 在mySQL中,dateOfBirth列的类型是DATE 当我试图保存我的记录时,我得到了不兼容的转换。我该怎么处理?日期字段为DOR和DOB 我试图定义一种格式:用Java处理日期,java,mysql,Java,Mysql,我不熟悉JavaGUI 我有一个保存到mySQL的简单数据输入表单。在我定义的文本框中有dateOfBirth 在mySQL中,dateOfBirth列的类型是DATE 当我试图保存我的记录时,我得到了不兼容的转换。我该怎么处理?日期字段为DOR和DOB 我试图定义一种格式: DateFormat df= new SimpleDateFormat("dd/MM/yyyy"); 并将变量DOR或DOB重新定义为字符串: String DOB = new String(); 然后在插入数据库时,
DateFormat df= new SimpleDateFormat("dd/MM/yyyy");
并将变量DOR或DOB重新定义为字符串:
String DOB = new String();
然后在插入数据库时,将变量格式化如下:
格式(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);
首先,我不会将该查询用于插入。你应该使用事先准备好的陈述。它比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();
因为DOB似乎是一个字符串,而不是一个日期,它对格式没有任何作用。请阅读PreparedStatements。不要自己逃避查询参数。为什么要将日期建模为字符串?MySQL日期格式为yyyy-MM-dd HH:MM:ssThank@MihaiC,如何将在swing文本框中输入的值(我假设它默认为字符串)分配给DOB而不出现错误?@Sylvester如果DOB是字符串,请从文本框DOB=textbox.getText()复制该值;在将值设置为prepared语句之前,将其转换为java.sql.Date。该字符串必须以您稍后转换日期时使用的相同格式输入,因此在这种情况下,用户必须以该格式写入2014年12月31日或任何日期。对不起,我无法理解日期格式。我曾广泛使用vb.net,但我似乎无法理解为了将字段保存到数据库中而必须执行的多行代码。“我正在梳理网络,但没有发现任何精确的东西。”西尔维斯特我补充了一些评论,希望它们是清楚的。您可以从javadocs中阅读更多关于所使用的类和方法的信息。然后,您将了解它们采用的参数以及它们返回的对象或值。