애플리케이션과 데이터베이스를 연결해봅시다.
public abstract class ConnectionConst {
//...1-a
public static final String URL = "jdbc:h2:tcp://localhost/~/h2db/jdbc";
public static final String USERNAME = "sa";
public static final String PASSWORD = "";
}
이제 JDBC를 사용해서 실제 데이터베이스에 연결하는 코드를 작성해보죠.
package hello.jdbc.connection;
import lombok.extern.slf4j.Slf4j;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import static hello.jdbc.connection.ConnectionConst.PASSWORD;
import static hello.jdbc.connection.ConnectionConst.URL;
import static hello.jdbc.connection.ConnectionConst.USERNAME;
@Slf4j
public class DBConnectionUtil {
//...1
public static Connection getConnection() {
try {
//...2
Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
log.info("get connection={}, class={}", connection, connection.getClass());
return connection;
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
}
java.sql.Connection
을 import 해야합니다.데이터베이스에 연결하려면 JDBC가 제공하는 DriverManager.getConnection 메서드를 사용하면 됩니다.
이렇게 하면 라이브러리에 있는 데이터베이스 드라이버를 찾아서 해당 드라이버가 제공하는 커넥션을 반환해줍니다.
→ 자세히
여기서는 H2 데이터베이스 드라이버가 작동해서 실제 데이터베이스와 커넥션을 맺고 그 결과를 반환해줍니다.
간단한 학습용 테스트 코드를 만들어서 실행해보죠.
@Slf4j
class DBConnectionUtilTest {
@Test
void connection() {
Connection connection = DBConnectionUtil.getConnection();
assertThat(connection).isNotNull();
}
}