同学你好,使用java.sql.Date中的valueOf()方法,将字符串类型的日期格式转换为java.sql.Date类型的日期,并将catch中打印异常信息修改为具体的提示信息试下。参考代码如下:
import com.imooc.jdbc.common.DbUtils;
import com.imooc.jdbc.hrapp.command.Command;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.util.Scanner;
public class InsertCommand implements Command {
public static void main(String[] args) {
new InsertCommand().execute();
}
@Override
public void execute() {
Scanner sc = new Scanner(System.in);
System.out.println("已进入插入部门员工信息程序:");
System.out.println("请输入员工编号:");
Integer ineno = sc.nextInt();
System.out.println("请输入员工姓名:");
String inename = sc.next();
System.out.println("请输入员工工资:");
Float insalary = sc.nextFloat();
System.out.println("请输入员工部门:");
String indname = sc.next();
System.out.println("请输入员工入职日期:");
String inhiredate = sc.next();
Date date = null;
Connection con = null;
PreparedStatement pstmt = null;
try {
date = Date.valueOf(inhiredate);
con = DbUtils.getConnection();
pstmt = con.prepareStatement("insert into employee (eno,ename,salary,dname,hiredate) values (?,?,?,?,?)");
pstmt.setInt(1, ineno);
pstmt.setString(2, inename);
pstmt.setFloat(3, insalary);
pstmt.setString(4, indname);
pstmt.setDate(5, date);
int c = pstmt.executeUpdate();
System.out.println("已成功插入" + c + "条员工信息");
} catch (ClassNotFoundException e) {
System.out.println("驱动类加载失败");
} catch (Exception throwables) {
System.out.println("输入有误,添加失败");
} finally {
DbUtils.closeConnection(null, pstmt, con);
}
}
}
另外建议同学可以将具体的报错信息复制粘贴或截图上传至问答区,便于快速的定位问题。
祝学习愉快~
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星