JDBC 실습2 - insert

oyeon·2021년 1월 4일
0
post-custom-banner

프로젝트 실습

목표 : role 테이블에 insert로 새로운 row 추가

  1. RoleDao.java 코드작성
package kr.or.connect.jdbcexam.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import kr.or.connect.jdbcexam.dto.Role;

public class RoleDao {
	private static String dburl = "jdbc:mysql://localhost:3306/connectdb?serverTimezone=UTC";
	private static String dbUser = "connectuser";
	private static String dbpasswd = "PASSWORD";

	public int addRole(Role role) {
		int insertCount = 0; // OO건 입력했습니다. OO결과를 담을 변수
		Connection conn = null;
		PreparedStatement ps = null;

		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			conn = DriverManager.getConnection(dburl, dbUser, dbpasswd);

			String sql = "INSERT INTO role (role_id, description) VALUES ( ?, ? )";
			ps = conn.prepareStatement(sql);

			ps.setInt(1, role.getRoleId());
			ps.setString(2, role.getDescription());

			insertCount = ps.executeUpdate();

		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (ps != null) {
				try {
					ps.close();
				} catch (Exception ex) {
				}
			} // if
			if (conn != null) {
				try {
					conn.close();
				} catch (Exception ex) {
				}
			} // if
		} // finally
		return insertCount;
	}
}
  1. 실행코드작성
package kr.or.connect.jdbcexam;

import kr.or.connect.jdbcexam.dao.RoleDao;
import kr.or.connect.jdbcexam.dto.Role;

public class JDBCExam2 {
	public static void main(String[] args) {
		int roleId = 500;
		String description = "CTO";
		
		Role role = new Role(roleId, description);
		
		RoleDao dao = new RoleDao();
		int insertCount = dao.addRole(role);
		
		System.out.println(insertCount);
	}
}

결과

profile
Enjoy to study
post-custom-banner

0개의 댓글