유블로그

[Java] JDBC API 기본 사용법 본문

DB

[Java] JDBC API 기본 사용법

yujeong kang 2020. 10. 21. 01:46
package com.ssafy.jdbc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/*
 * JDBC 작업 순서
 * 1. Driver Loading
 * 2. DB 연결 (Connection 생성)
 * 3. SQL 실행 준비
 *   3-1. SQL 작성.
 *   3-2. Statement 생성 (Statement, PreparedStatement)
 * 4. SQL 실행
 *   4-1. I, U, D
 *      int x = stmt.execteUpdate(sql);
 *   	int x = pstmt.executeUpdate();
 *   4-2. S
 *      ResultSet rs = pstmt.executeQuery();
 *      rs.next() [단독, if, while]
 *      값얻기 : rs.getString()
 *            rs.getInt() 등등등....
 * 5. DB 연결 종료 : 연결 역순으로 종료, finally
 * 	if(rs != null)
 *    	rs.close()
 *  if(pstmt != null)
 *  	pstmt.close();
 *  if(conn != null)
 *  	conn.close();
 */
public class JdbcTest {
	
	private final String driver = "com.mysql.cj.jdbc.Driver";
	private final String url = "jdbc:mysql://127.0.0.1:3306/디비이름?serverTimezone=UTC&useUniCode=yes&characterEncoding=UTF-8";
	private final String dbid = "...";
	private final String dbpwd = "...";
	
	public static void main(String[] args) throws IOException {
		Connection conn;
		PreparedStatement pstmt;
		ResultSet rs;
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, dbid, dbpwd);
			pstmt = conn.prepareStatement("select * from student where num = ?");
			pstmt.setInt(1, 10);
			rs = pstmt.execute();
			JdbcDto dto = new JdbcDto ();
			if (rs.next()) {
				dto.setNum(rs.getInt("num"));
				dto.setName(rs.getString("name"));
			}
			System.out.println(dto);
            
                        if(rs != null)
                        rs.close()
                        if(pstmt != null)
                        pstmt.close();
                        if(conn != null)
                        conn.close();
                
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
	}
}

'DB' 카테고리의 다른 글

데이터베이스 모델링  (0) 2020.10.21