- Java DataBase Connectivity
- Java와 DB연결을 위한 표준 API
Class.forName()
Class 라는 이름을 가진 클래스는 JVM에서 동작할 클래스들의 정보를 묘사하는 일종의 메타클래스.
데이터 베이스와 연결할 드라이버 클래스를 찾아서 로드하는 역할.
conn = DriverManager.getConnection(url, id, pw)
선언한 conn에 생성된 Connection 객체대입
public class DBConnection {
public static void initConnection() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Driver Loading Success");
} catch (ClassNotFoundException e) {
System.out.println("DB Drive를 찾지 못했습니다");
e.printStackTrace();
}
}
public static Connection getConnection() {
// url -> localhost대신 본인ip주소 입력해도 됨 (mysql에서 외부 접속 허용)
String url = "jdbc:mysql://localhost:3306/mydb"
String id = "root";
String pw = "1234";
Connection conn = null;
try {
conn = DriverManager.getConnection(url, id, pw);
System.out.println("Connection Success");
} catch (SQLException e) {
System.out.println("db를 연결하지 못했습니다");
e.printStackTrace();
}
return conn;
}
}
Connection
: DB와 연결하기 위한 인터페이스
Statement
: SQL을 보내기 위한 통로
ResultSet
: SQL문의 결과를 저장하는 객체
public class DBClose {
public static void close(Connection conn, Statement psmt, ResultSet rs) {
try {
if(conn != null) {
conn.close();
}
if(psmt != null) {
psmt.close();
}
if(rs != null ) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
https://m.blog.naver.com/rnalsttnn2/222099599178
https://yoon990.tistory.com/58