if (cmd.equals("article write")) {
System.out.println("== 게시물 작성 ==");
System.out.printf("제목 : ");
String title = sc.nextLine();
System.out.printf("내용 : ");
String body = sc.nextLine();
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/article_manageruseUnicode=
true&characterEncoding=utf8&autoReconnect=true&serverTimezone=
Asia/Seoul&useOldAliasMetadataBehavior=
true&zeroDateTimeNehavior=convertToNull";
conn = DriverManager.getConnection(url, "root", "");
System.out.println("연결 성공!");
String sql = "INSERT INTO article";
sql += " SET regDate = NOW()";
sql += ",updateDate = NOW()";
sql += ",title = " + "'" + title + "'";
sql += ",`body` = " + "'" + body + "';";
System.out.println(sql);
pstmt = conn.prepareStatement(sql);
int affectedRows = pstmt.executeUpdate();
System.out.println("affectedRows : " + affectedRows);
} catch (ClassNotFoundException e) {
System.out.println("드라이버 로딩 실패");
} catch (SQLException e) {
System.out.println("에러: " + e);
} finally {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}try {
if (pstmt != null && !pstmt.isClosed()) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
1 . JDBC 드라이버 로드
Class.forName("com.mysql.jdbc.Driver");
2 . 데이터베이스 연결
String url = "jdbc:mysql://127.0.0.1:3306/article_manageruseUnicode
=true&characterEncoding=utf8&autoReconnect=true&server
Timezone=Asia/Seoul&useOldAliasMetadataBehavior=true&zeroDateTimeNehavior
=convertToNull";
conn = DriverManager.getConnection(url, "root", "");
3 . SQL을 위한 Statement 객체 생성
PreparedStatement pstmt = null;
String sql = "실행할 sql문";
pstmt = conn.prepareStatement(sql);
4 . SQL 문장 실행
int affectedRows = pstmt.executeUpdate();
5 . JDBC 객체 연결 해제
conn.close();
pstmt.close();