Reputation: 21
I am trying to insert a row in the mysql database using Java jdbc connectivity....
Here is my code,
public class DBPreparedStatement2 {
public static void main(String[] args) throws ParseException{
try {
ArrayList<Student> slist = new ArrayList<Student>();
String sDate1="1998/11/04";
java.sql.Date dob=(java.sql.Date) new SimpleDateFormat("yyyy/MM/dd").parse(sDate1);
slist.add(new Student(6,"James","Bond",dob,10,"[email protected]"));
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/school","root","root");
String insertCommand="INSERT INTO STUDENTS VALUES(?,?,?,?,?,?)";
PreparedStatement ps=con.prepareStatement(insertCommand);
for(Student student:slist) {
ps.setInt(1, student.id);
ps.setString(2, student.firstName);
ps.setString(3, student.lastName);
ps.setDate(4, student.dob);
ps.setInt(5, student.studClass);
ps.setString(6, student.email);
}
}catch(ClassNotFoundException e1) {
e1.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();
}
}
}
When I try to run the code I'm getting class cast exception... Some help would be greatly appreciated. Here is my Student.java class
import java.sql.Date;
public class Student {
int id;
String firstName;
String lastName;
Date dob;
int studClass;
String email;
public Student() { }
public Student(int id,String firstName,String lastName,java.sql.Date dob,int studClass,String email) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
this.studClass = studClass;
this.email = email;
}
}
when I run the code I am getting the following error: Exception in thread "main" java.lang.ClassCastException: class java.util.Date cannot be cast to class java.sql.Date (java.util.Date is in module java.base of loader 'bootstrap'; java.sql.Date is in module java.sql of loader 'platform') at jdbcsample.DBPreparedStatement2.main(DBPreparedStatement2.java:25)
Upvotes: 1
Views: 668
Reputation: 3166
Your exception comes from this line:
java.sql.Date dob = (java.sql.Date) new SimpleDateFormat("yyyy/MM/dd").parse(sDate1);
since parse will return a java.util.Date
, not a java.sql.Date
. You cannot cast to a java.sql.Date
since the two are not related.
You can get rid of it by instansiating a java.sql.Date
with
java.sql.Date dob = new java.sql.Date(new SimpleDateFormat("yyyy/MM/dd")
.parse(sDate1)
.getTime());
but I'd recommend you avoid using java.util.Date
, and instead use:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.parse(sDate1, formatter);
java.sql.Date dob = java.sql.Date.valueOf(localDate);
Upvotes: 1