자바 공부/자바

자바 - JDBC

ari0930 2024. 4. 10. 23:25

자바 - JDBC

 

자바를 이용하여 mysql 접속하여 데이터 수정 및 조회하는 방법( mysql 8.0 이상버전)

 
기본적으로 jdbc를 이용하는방법

  1. import java.sql.* 한다.
  2. 드라이브를 로드한다.=> Class.forName("com.mysql.cj.jdbc.Driver");
  3. connection 객체를 생성한다.
  4. statement 객체를 생성하의 쿼리문을 실행할수 있도록 한다.
  5. 결과를 얻었으면 만들었던 객체를 모두닫는다.

 
db로 부터 우리가원하는값을 저장할수 있는 객체를 만든다
나는 roleId,description 는 내용을 받아올거다.

package kr.or.connect.jdbcexam.dto;

public class Role {
	private Integer roleId;
	private String description;

	public Role() {

	}

	public Role(Integer roleId, String description) {
		super();
		this.roleId = roleId;
		this.description = description;
	}

	public Integer getRoleId() {
		return roleId;
	}

	public void setRoleId(Integer roleId) {
		this.roleId = roleId;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	@Override
	public String toString() {
		return "Role [roleId=" + roleId + ", description=" + description + "]";
	}
}

 
db에 접속할수 있도록 하는 메서드를 만든다.
 

	private static String dbUrl = "jdbc:mysql://localhost:3306/db이름?allowPublicKeyRetrieval=true";
	private static String dbUser = "db계정";
	private static String dbpasswd = "비번";

접속할 db 이름과 그 db 계정과 비밀번호를 이용해야하기에 이렇게 윗부분에 선언한다.
 

특정값을 가져오기 위한 메서드

	public Role getRole(Integer roleId) {
		Role role = null;
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			conn = DriverManager.getConnection(dbUrl, dbUser, dbpasswd);
			String sql = "SELECT description,role_id FROM role WHERE role_id = ?";  //어떤명령 수행
			ps = conn.prepareStatement(sql); 
			ps.setInt(1, roleId); //첫번째 물은표에 , 뒤의 값을 너어라
			rs = ps.executeQuery();//수행한 결과 저장

			if (rs.next()) { 
				String description = rs.getString(1);//값 꺼내기 첫번째열
				int id = rs.getInt("role_id"); //값 꺼내기
				role = new Role(id, description);//이 객체에 담아서 보낸다
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

		return role;
	}

Role role = null;      => 받아올 정보를 저장하기 위해 만든 객체
Connection conn = null;    =>db접속을 위해 드라이버 연결을 위해 사용하는 객체
PreparedStatement ps = null;   => db에 우리가 원하는 값을 찾기 위한 명령을 실행하도록 하는 객체
ResultSet rs = null;  => 명령을 수행한 값을 저장하기 위한 객
 
String sql = "SELECT description,role_id FROM role WHERE role_id = ?";  이란 코드는 내가 수행하고자 하는  sql 명령어 이다 나는  description,role_id  값을 가져오고 싶기에  SELECT 를 이용하여 값을 가져오도록하였다

 
이걸 실행시키는 코드

		RoleDao dao = new RoleDao();
		Role role = dao.getRole(100); //객체선언과 동시에 반환하는거다
		System.out.println(role);

이렇게 실행하면  role_id가 100 인값의  description 의 내용물과 id값이 반환된다.
 
 

db에 새로운 값을 추가하는 메서드

public int addRole(Role role) {
		int insertCount=0;

		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());//넣어주는 데이터 타입에 따라 setint,string 

			insertCount=ps.executeUpdate();




		} catch (Exception ex) {
			// TODO: handle exception
			ex.printStackTrace();
		}finally {
			if(ps != null) {
				try {
					ps.close();
				} catch (Exception ex) {}
			}
			// TODO: handle exception
			if(conn!=null) {
				try {
					conn.close();

				} catch (Exception ex) {}

			}
		}

		return insertCount;
	}

값을 조회하는 위의 메서드하고 동일하게 진행되는데 차이는 결과값을 저장할 메서드는 필요없다 우린 값을 추가할거기 때문이다.
 
INSERT INTO role (role_id,description) VALUES (?,?)  이문장은  role_id,description 에 
ps.setInt(1, role.getRoleId()); 
ps.setString(2, role.getDescription());
위 코드를 이용하여 role 객체에 들어있는 값을 넣을수 있다 
 
위코드 실행하는 코드

		int roleId=501;
		String descriptionString ="cto";
		
		Role data = new Role(roleId,descriptionString);
		int insertCount=dao.addRole(data);

roleId 가 501이고 description 값이 cto 라는 role 객체가 만들어져 addRole 에 들어가
addRole 의 아래 코드들의 의해 값이 db에 저장된다 
ps.setInt(1, role.getRoleId()); 
ps.setString(2, role.getDescription()); 
 

값을 삭제하는 메서드

	public int deleteRole(Integer  roleId) {
		int deleteCount =0;

		Connection conn =null;
		PreparedStatement ps =null;
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			conn = DriverManager.getConnection(dbUrl, dbUser, dbpasswd);
			String sql = "DELETE FROM role WHERE role_id = ?";//어떤명령 수행

			ps=conn.prepareStatement(sql);
			ps.setInt(1, roleId); //?된 부분의 값을 넣어주는 역할 
			

			deleteCount =ps.executeUpdate();




		} catch (Exception ex) {
			// TODO: handle exception
			ex.printStackTrace();
		}finally {
			if(ps != null) {
				try {
					ps.close();
				} catch (Exception ex) {}
			}
			// TODO: handle exception
			if(conn!=null) {
				try {
					conn.close();

				} catch (Exception ex) {}

			}
		}

		return deleteCount ;
	}

값을 삭제하기위해서 조회하기와 비슷하게 roleId 값만 받아와서 roleId과 같은값을 찾아 그부분을 삭제한다.
 
실해하는 코드

		RoleDao dao = new RoleDao();
		Role role = dao.getRole(100); //객체선언과 동시에 반환하는거
		//삭제
		int deleteCount= dao.deleteRole(roleId);

이렇게 하면 100이라는 값을 가진 부분을 삭제할수있다.
 

내용 업데이트 하는 메서드

//값 업데이트 
	public int updateRole(Role role) {
		int updateCount=0;

		Connection conn =null;
		PreparedStatement ps =null;
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			conn = DriverManager.getConnection(dbUrl, dbUser, dbpasswd);
			String sql = "update role set description = ? where role_id = ?";

			ps=conn.prepareStatement(sql);
			ps.setInt(2, role.getRoleId()); //?된 부분의 값을 넣어주는 역할 
			ps.setString(1, role.getDescription());//넣어주는 데이터 타입에 따라 setint,string 

			updateCount=ps.executeUpdate();




		} catch (Exception ex) {
			// TODO: handle exception
			ex.printStackTrace();
		}finally {
			if(ps != null) {
				try {
					ps.close();
				} catch (Exception ex) {}
			}
			// TODO: handle exception
			if(conn!=null) {
				try {
					conn.close();

				} catch (Exception ex) {}

			}
		}

		return updateCount;
	}

값을 업데이트 하기 위해서description 내용을 바꾸기 위해  role에 객체에 바꿀 내용을 넣어서 받아와서 수정한다.
 
실행하는 코드

		Role update = new Role(100,"update");
		int updateCount =dao.updateRole(update);

role 객체에 수정할 값을 넣어서 만든다.
 
 

db안의 모든 데이터 조회하기

	public List<Role> getRoles() {
		List<Role> list = new ArrayList<>();

		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		String sql = "SELECT description, role_id FROM role order by role_id desc";
		try (Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbpasswd);
				PreparedStatement ps = conn.prepareStatement(sql)){ 
		//자동으로 클로즈 해주는 

			try (ResultSet rs = ps.executeQuery()) {

				while (rs.next()) {
					String description = rs.getString(1);
					int id = rs.getInt("role_id");
					Role role = new Role(id, description);
					list.add(role); // list에 반복할때마다 Role인스턴스를 생성하여 list에 추가한다.
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return list;
	}

 
실행하는 코드문

		List<Role> list =dao.getRoles();
		for (Role role2 : list) {
			System.out.println(role2);
		}
반응형

'자바 공부 > 자바' 카테고리의 다른 글

자바 추상클래스,인터페이스  (1) 2024.04.14
자바 접근제한자  (0) 2024.04.10
자바 클래스  (0) 2024.04.10
자바 메서드  (0) 2024.04.05
[자바] 변수 선언,데이터 타입,  (0) 2024.02.02