【发布时间】:2020-08-11 14:10:02
【问题描述】:
我正在尝试使用 Java jdbc 连接在 mysql 数据库中插入一行......
这是我的代码,
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,"jb@yahoo.com"));
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();
}
}
}
当我尝试运行代码时,我得到了类转换异常...... 一些帮助将不胜感激。 这是我的 Student.java 类
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;
}
}
当我运行代码时,我收到以下错误: 线程“主”java.lang.ClassCastException 中的异常:类 java.util.Date 无法转换为 类 java.sql.Date(java.util.Date 位于加载器“bootstrap”的模块 java.base 中;java.sql.Date 在加载器“平台”的模块 java.sql 中) 在 jdbcsample.DBPreparedStatement2.main(DBPreparedStatement2.java:25)
【问题讨论】:
-
你确定学生班的
date是java.sql.date -
是的,它是 java.sql.date
-
Class.forName("com.mysql.jdbc.Driver");需要至少 10 年了;你应该找到一些最近写的教程材料。