lundi 2 décembre 2019

How can I insert data to MySQL?

public void insertBoard(BoardDTO board) {
    Connection conn = null;
    Statement stmt = null;
    try {
        conn = this.getConnection();
        conn.setAutoCommit(false);
        stmt = conn.createStatement();

        String sql = "INSERT INTO board (TITLE, SUB_TITLE, CONTENTS, CREATE_DATE) VALUES"
                + "('"+board.getTitle()+"', '"
                + board.getSubTitle()+"', '"
                + board.getContents()+"', '"
                + board.getFormatCreateDate()+"')";
        stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
        ResultSet resultSet = stmt.getGeneratedKeys();
        resultSet.next();
        board.setId(resultSet.getInt(1));
        sql = "INSERT INTO attach_file (BOARD_ID, PATH, ORIGINAL_FILE_NAME, SAVE_FILE_NAME) VALUES"
                + "(" + board.getId() +", '"
                + board.getAttachFile().getPath()+"', '"
                + board.getAttachFile().getOriginalFileName()+"', '"
                + board.getAttachFile().getSaveFileName()+"')";
        stmt.executeUpdate(sql);
        conn.commit();

    } catch (SQLException | ClassNotFoundException e) {
        try {
            conn.rollback();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
    } finally {
        try {
            if(stmt != null) stmt.close();
            if(conn != null) conn.close();
        } catch(SQLException e) {
            e.printStackTrace();
        }
    }
}

I trying to make board on my test website. I was build that code on my 'FrontController.java' servlet. after that I run my website and insert some data on that page, but I couldn't find any data on my SQL tables. is ther any problem on that code?

public class UserDTO {
private String id;
private String email;
private String password;
private int job;
private String gender;
private String introduction;
private Date createDate;

public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;

 .... setter and getters ....

public String getFormatCreateDate() {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return dateFormat.format(this.createDate);
}

that's my BoardDTO code




Aucun commentaire:

Enregistrer un commentaire