Notice
Recent Posts
Recent Comments
Link
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
Tags
more
Archives
Today
Total
관리 메뉴

WON.dev

chapter02 : insert 본문

JAVA/chapter27_preparestatement

chapter02 : insert

GAWON 2023. 5. 31. 09:38
package org.joonzis.ex;

import java.sql.Connection;
import java.sql.PreparedStatement;

import org.joonzis.db.DBConnection;

public class Ex01_insert {
	public static void main(String[] args) {

		Connection conn = null;
		PreparedStatement ps = null; // sql의 값을 변수 처리 할 수 있다.

		try {
			conn = DBConnection.getConnection();

			String sql = "insert into person(name, age, region) values(?, ?, ?)"; // 나중에 setter로 채울 수 있다.
			ps = conn.prepareStatement(sql); // 미리 sql을 생성해야 함

			// ?에 데이터 set
			ps.setString(1, "김씨");
			ps.setInt(2, 50);
			ps.setString(3, "부산");

			int result = ps.executeUpdate();

			// 삽입성고 : 1 ,실패 : 0
			if (result > 0) {
				System.out.println("삽입 성공!");
			} else {
				System.out.println("삽입 실패");
			}

			conn.commit();

		} catch (Exception e) {
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (Exception e2) {

			}
		} finally {
			try {
				if (ps != null) {
					ps.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}

		}
	}

}

'JAVA > chapter27_preparestatement' 카테고리의 다른 글

chapter05 : select  (0) 2023.05.31
chapter04 : delete  (0) 2023.05.31
chapter03 : update  (0) 2023.05.31
chapter01 : DBConnection  (0) 2023.05.31