[자바 JDBC 게시판] 1일차

김정현·2022년 8월 8일

JDBC게시판

목록 보기
1/9
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");
  • Class 클래스의 forName() 메소드를 사용해서 드라이버를 로드한다
    forName(String className) 메소드는 문자열로 주어진 클래스나 인터페이스 이름을 객체로 리턴한다.

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";
  • url은 데이터베이스 주소를 의미한다.
conn = DriverManager.getConnection(url, "root", "");
  • 서버와 연결해주는 역할을 하는 DriverManager의 getConnection 메소드를 통해 매개변수로
    서버 주소와 아이디, 비밀번호를 넘겨주어 연결한다.

3 . SQL을 위한 Statement 객체 생성

PreparedStatement pstmt = null;

String sql = "실행할 sql문";

pstmt = conn.prepareStatement(sql);
  • PreparedStatement 클래스는 sql문을 실행시켜 주는 역할을 하는 클래스
    연결한 객체를 통해 prepareStatement() 메소드에 접근하여 담긴 sql문장을 대입
  • prepareStatement() : 데이터베이스로 쿼리를 담아서 전송할 수 있는 메소드

4 . SQL 문장 실행

int affectedRows = pstmt.executeUpdate();
  • executeUpdate()메소드를 사용해서 쿼리를 처리

5 . JDBC 객체 연결 해제

conn.close();

pstmt.close();

JDBC,DMBS연동 관련 자료사이트


🔍 객체출력

  • System.out.println("객체"); 모든 클래스는 object를 상속받는다.
    object의 .toString()를 상속받으므로 .toString() 메소드를 오버라이드(재정의)하여 사용할수있다.

🔍 JDBC Driver 프로젝트에 적용

  • Maven Repository -> 라이브러리들을 모아 놓은 사이트
  • mysql connecter J(JDBC Driver)를 프로젝트에 적용 시키기위해 프로젝트안에 드라이버 파일을 담고 Build Path -> Add to Build Path 클릭해야 적용
    (Reperenced Libraries 생성)

0개의 댓글