JDBC中Date日期物件的處理

GiantApe發表於2020-10-12

JDBC中Date日期物件的處理

package com.imooc.jdbc.hrapp.command;

import com.imooc.jdbc.goodapp.common.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

/**
 * @author CubeMonkey
 * @create 2020-10-11 10:03
 */
public class InsertCommand implements Command {
    @Override
    public void execute() {
        Scanner in = new Scanner(System.in);
        System.out.print("請輸入員工編號:");
        int eno = in.nextInt();
        System.out.print("請輸入員工姓名:");
        String ename = in.next();
        System.out.print("請輸入員工薪資:");
        float salary = in.nextFloat();
        System.out.print("請輸入隸屬部門:");
        String dname = in.next();
        System.out.print("請輸入入職日期:");
        String strHiredate = in.next();
        //String到java.sql.Date分兩步
        //1.String轉為java.util.date;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date udHiredate = null;
        try {
            udHiredate = sdf.parse(strHiredate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //2.java.util.date轉為java.sql.date
        java.sql.Date sdHiredate = new java.sql.Date(udHiredate.getTime());

        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = DBUtils.getConnection();
            String sql = "insert into employee(eno, ename, salary, dname, hiredate) values(?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, eno);
            pstmt.setString(2, ename);
            pstmt.setFloat(3, salary);
            pstmt.setString(4, dname);

            pstmt.setDate(5, sdHiredate);

            int cnt = pstmt.executeUpdate();
            System.out.println("cnt:"+cnt);
            System.out.println(ename + "員工入職手續已辦理");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtils.closeConnection(null, pstmt, conn);
        }
    }
}

相關文章