Reputation: 125
I am new to java GUI
I have a form for simple data input that saved to mySQL. Among the textboxes I have defined is dateOfBirth.
In mySQL, the dateOfBirth column is type DATE.
When I attempt to save my record, I get incompatible conversions. How Do I handle this? The Date fields are DOR and DOB.
I tried to define a format :
DateFormat df= new SimpleDateFormat("dd/MM/yyyy");
and also changed redefined the var DOR or DOB as String:
String DOB = new String();
then when inserting into database, formatted the var like this: df.format(DOB)
I still got the error: "Error: Cannot format given object as a Date". What to do?
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);
Upvotes: 0
Views: 110
Reputation: 1583
First of all i would not use that query for the insert. You should use a prepared statement. It's safer against sql injection.
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();
Upvotes: 1