JAVA

JDBC(Java DataBase Connectivity)

이충무 2022. 9. 21. 00:14

JDBC 작업 순서


  1. Driver Loading
  2. DB 연결 (Connection 생성)
  3. SQL 실행 준비
    1. SQL 작성.
    2. Statement 생성 (Statement, PreparedStatement)
  4. SQL 실행
    1. I, U, D
    2. S
int x = stmt.execteUpdate(sql);

int x = pstmt.executeUpdate();
ResultSet rs = pstmt.executeQuery();

rs.next() [단독, if, while]`

값얻기 : rs.getString()

rs.getInt() 등등등....

5. DB 연결 종료 : 연결 역순으로 종료, finally, AutoCloseable, try-with-resource (JDK7이상)

if(rs != null)
	rs.close()

if(pstmt != null)
	pstmt.close();

if(conn != null)
	conn.close();

 

public class DMLTest {
	//1-1. 드라이버 로딩 : 생성자 속에 구현(빌드패스 꼭 잡아주기 -> C:\\Program Files (x86)\\MySQL\\Connector J 8.0\\mysql-connector-java-8.0.30.jar - 외부자르 추가)
	public DMLTest() {
		//com.mysql.cj.jdbc.Driver은 일종의 약속
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			System.out.println("드라이버 로딩 성공!");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}
	public static void main(String[] args) {
		//1-2. 객체 생성(생성자에 의한 드라이버 로딩)
		DMLTest dmlTest = new DMLTest();
		
		dmlTest.insertProduct("S1234", "갤럭시S23",1600000, "작게 나왔어요." );
	}
	private void insertProduct(String productId,String productName,int productPrice,String productDesc) {
		Connection conn = null;
		PreparedStatement pstmt=null;
		try {
			//2. DB 연결 - Connection 생성
			//Connection conn = DriverManager.getConnection("url", "userid", "password");
			conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/scott?serverTimezone=UTC&useUniCode=yes&characterEncoding=UTF-8", "ssafy", "ssafy");
			
			//3-1 SQL문 작성(매개변수로 넘겨줄 String 형태로 sql문 작성 , ?형태의 위치 홀더 사용)
			String sql = "insert into product(product_id, product_name,product_price,product_desc)";
			sql+="values(?,?,?,?)";
			
			//3-2 SQL문 실행을 위한 preparedStatement 객체 생성
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, productId);
			pstmt.setString(2, productName);
			pstmt.setInt(3, productPrice);
			pstmt.setString(4, productDesc);
			
			//4. SQL문 실행  --> prepareStatement 실행
			int cnt = pstmt.executeUpdate();
			System.out.println(cnt + "개 삽입 완료!");
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			//5. DB연결 종료
			try {
				if(pstmt != null) {
					pstmt.close();
				}
				if(conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}

}