SQL Insert 할 때, VALUES (?,?,?,?) & PreparedStatement 사용

박영준·2024년 6월 10일
0

JDBC

목록 보기
5/7

기존의 코드

import java.sql.*;

public class Program {
	
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
			
		String url = "jdbc:oracle:thin:@localhost:1521:ORCL";		
		String sql = "SELECT * FROM BOARD";						
		
		Class.forName("oracle.jdbc.driver.OracleDriver");
		Connection con = DriverManager.getConnection(url, "데이터베이스ID", "데이터베이스PW");		
		Statement st = con.createStatement();				
		ResultSet rs = st.executeQuery(sql);		
		
		if(rs.next() ) {
			String title = rs.getString("TITLE");				
			System.out.println(title);						
		};										
		
		rs.close();	
		st.close();		
		con.close();	
	}
}

VALUES (?,?,?,?) & PreparedStatement 사용하기

import java.sql.*;

public class Program {
	
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
			
        1. DB 에 Insert 할 데이터    
		String title = "TEST1";
		String writerId = "intarware";
		String content = "hahah";
		String files = "";
		
		String url = "jdbc:oracle:thin:@localhost:1521:ORCL";
		
		// 2. JDBC에서 지원하는 기능 VALUES (?,?,?,?)
		String sql = "INTSERT INTO BOARD ( " +
				" 	title," +
				" 	wirter_id," +
				" 	content," +
				" 	files" +
				") VALUES (?,?,?,?)";						
		
		Class.forName("oracle.jdbc.driver.OracleDriver");
		Connection con = DriverManager.getConnection(url, "데이터베이스ID", "데이터베이스PW");	
		
        // 3. PreparedStatement 을 사용하여 VALUES (?,?,?,?) 에 값을 채우기
		PreparedStatement st = con.prepareStatement(sql);		
		st.setString(1, title);
		st.setString(2, writerId);
		st.setString(3, content);
		st.setString(4, files);
						
        // 4. 실행                
		int result = st.executeUpdate();
		
		System.out.println(result);

	}
}
  1. JDBC에서 지원하는 기능 VALUES (?,?,?,?)

    • 기존에는 작은따옴표를 이용하여 '+title+'과 같이 사용해야했으나, ?로 대체해도 해당 컬럼에 데이터를 Insert 할 수 있게 되었다.
  2. PreparedStatement 을 사용하여 VALUES (?,?,?,?) 에 값을 채우기

    • PreparedStatement : 쿼리문에 미리(prepared) 값을 채워넣어서 실행만 하면 되게끔 준비해둔다
    • ? 는 각 컬럼
    • VALUES (?,?,?,?) 에서 인덱스는 1부터 시작(0부터 시작 x)
    • setString : 각 데이터의 타입에 따라 String, Int 등... 을 사용해줄 수 있다
  3. 실행

    • 쿼리문이 SELECT 일 경우, executeQuery()
    • 쿼리문이 INSESRT 일 경우, executeUpdate()
profile
개발자로 거듭나기!

0개의 댓글