JPA를 위한 큰 그림 -> JDBC 튜토리얼

박경현·2023년 3월 27일
0

드디어 MySQL에서 JDBC로 넘어갔다!

JDBC를 해보면서 느낀점은 반복적인 몇가지 명령어만 안다면 사용이 쉽다는 것이다

JDBC 사용을 위한 설정!

JDBC를 사용하기 위해서 가장 중요한 거는 일단 MySQL이 켜져 있어야한다는 것이다!
그리고 MYSQL에 사용되는 DB와 User, pwd를 알고 있으면 바로 시작이 가능하다!

1.MYSQL 서버 확인 및 유저, DB, pwd 확인하기
2. 클래스 내 Connection과 DriverManager를 이용해서 연결하기!

public static void main(String [] args) {
	Connection conn = null;
    PreparedStatement ps = null;
    try {
    	conn = DriverManager.getConnection(
        		"jdbc:mysql://127.0.0.1:3306/examplesdb?useUnicode=true",
                "urstory",
                "u1234"
        	)
        if (conn!=null) {
        	System.out.println("DBMS성공!");
            System.out.println(conn.getClass().getName());
        }
        ps = conn.prepareStatement("insert into role(role_id, name) values (?,?)");
        ps.setInt(1,3); // index와 내가 넣을 값!
        ps.setString(2,"ROLE_SET");
        int updateCount = ps.executeUpdate();// insert update delete 할때 성공 건수 나옴! 지금은 1회
        
    
    } catch(SQLException ex) {
    	ystem.out.println("SQLException: "+ex.getMessage());
    } finally {
    	try {
        	conn.close();
            if(ps!=null) ps.close();
        }catch(SQLException e) { System.out.println("conn이 안닫힌다!"+e);}
    }

}

JDBC의 특징

JDBC는 DB에 접근 할 수 있도록 자바에서 제공하는 API이다.

sql, connection, preparedstatement, resultset으로 작성하면 된다!

connection 객체가 db와 app의 연결을 관리하고
preparedstatement가 sql을 전달하며
resultset 객체를 통해 결과 값을 전달한다.

DB 내 테이블 내용 조회 방법 - SELECT

public static void main(String [] args) {
	Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    
    try {
    	conn = DriverManager.getConnection (
        	"jdbc:mysql://127.0.0.1:3306/examplesdb?useUnicode=true",
            "urstory",
            "u1234"
        );
        ps = conn.prepareStatement("select role_id, name ");
        rs = ps.executeQuery();
        while (rs.next() ) {
        	int roleId = rs.getInt("role_id");
            String name = rs.getString("name");
            System.out.println(roleId + ": "+ name);
        	
        }
}
profile
SW로 문제를 해결하려는 열정만 있는 대학생

0개의 댓글