데이터베이스는 하나의 서버이기 때문에 원하는 데이터의 입출력, 수정 등을 하려면 데이터베이스 서버에 접속하고, sql명령을 요청해야 함
그와 같은 동작을 자바로 할 수 있도록 도와주는 API library가 JDBC
JDBC - Java Database Connectivity는 자바에서 데이터베이스에 접속할 수 있도록 하는 자바 API이다. JDBC는 데이터베이스에서 자료를 쿼리하거나 업데이트하는 방법을 제공한다. - 위키
Java(eclips), DB(postgresql), JDBD library 설치
JDBC(첫번째 jar파일) - https://jdbc.postgresql.org/download.html/
PostgreSQL JDBC Download
Download About Binary JAR file downloads of the JDBC driver are available here and the current version with Maven Repository. Because Java is platform neutral, it is a simple process of just downloading the appropriate JAR file and dropping it into your cl
jdbc.postgresql.org
DBMS(postsql) - https://www.postgresql.org/download/
PostgreSQL: Downloads
Downloads PostgreSQL Downloads PostgreSQL is available for download as ready-to-use packages or installers for various platforms, as well as a source code archive if you want to build it yourself. Packages and Installers Select your operating system family
www.postgresql.org
JAVA idle(eclips) - https://www.eclipse.org/downloads/
Eclipse Downloads | The Eclipse Foundation
The Eclipse Foundation - home to a global community, the Eclipse IDE, Jakarta EE and over 415 open source projects, including runtimes, tools and frameworks.
www.eclipse.org
(각 자바 버전 마다 호환하는 JDBC 버젼이 다르니 주의)
JDBC를 이용한 eclips -> DB 접속
1. eclips project 생성
2. Path에 jar 추가 : 생성한 프로젝트 우클릭 -> Properties -> Java Build Path -> Libraries -> Modulepath -> Add Library -> User Library -> User Libraries -> New -> 구별할 이름 넣기 (jdbc) -> ok -> 생성된 library 클릭 -> Add External JARs -> 다운받은 jdbc jar 파일 클릭 -> Apply and Close -> 새로 만들어진 Library 클릭 -> Finish -> Apply and Close
3. 메인 클래스 생성 후 다음 코드 입력
import java.sql.*;
public class Main {
public static void main(String[] args) throws Exception {
try {
Class.forName("org.postgresql.Driver");
//Class.forName() 을 이용해서 드라이버 로드
} catch (ClassNotFoundException e) {
System.out.println("failed");
e.printStackTrace();
return;
}
System.out.println("success");
/// if you have a error, check jdbc driver(jar file)
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/databaseName", "postgres", "1234");
//DriverManager.getConnection() 으로 연결 후 connection 인스턴스에 객체 저장
//데이터베이스 서버 주소 : 로컬호스트 + 연결하려는 데이터베이스 이름 + postgresql 서버의 포트번호(5432)
//데이터베이스에 접속할 계정의 id는 postgres 비밀번호는 1234
} catch (SQLException e) {
System.out.println("Failed");
e.printStackTrace();
return;
}
/// if you have a error, check DB information (db_name, user name, password)
if (connection != null) {
System.out.println(connection);
System.out.println("success");
} else {
System.out.println("Failed");
}
// write sql statement here!!!
connection.close();
}
}
DriverManager 클래스, Connection 객체 이해
DriverManager
DriverManeger 클래스는 위 class.forName() 메소드를 통해서 생성됩니다. class.forName("class name")은 특정 클래스를 로드하고 자동으로 객체를 생성한 후 DriverManager라는 위치에 등록시킵니다.
위에서 JDBC의 jar파일을 project에 이미 추가시켰으니 Class.forName("org.postgresql.Driver")으로 project안에 위치한 해당 클래스를 찾아 Driver manager에 등록될 것입니다.
Driver manager 클래스의 모든 메소드느 static이기 때문에 객체를 생성하지 않고 메소드를 사용할 수 있고,
Driver manager 클래스는 Connection 인터페이스의 구현 객체를 생성하는데 getConnection() 메소드를 사용합니다.
Connection
getConnection() 메소드로 얻은 인터페이스 객체인 Connection은 특정 데이터 원본과 연결된 커넥션을 나타냅니다.
데이터베이스에 대한 데이터인 메타데이터에 관한 정보를 데이터 원본에 질의하는데 사용합니다.
데이터베이스와 연결된 세션이고, 이 세션을 이용하여 데이버테이스에 SQL을 전송하고 그 결과인 Result객체를 얻어 냅니다.
Connection 객체 메소드
createStatement()
- SQL문을 DB에 전달하기 위한 Statement 객체를 생성한다.
preparedStatement(String sql)
- 파라미터가 포함된 SQL문을 DB에 전달하기 위한 preparedStatement 객체를 생성한다.
prepareCall(String sql)
- DB의 Stored Procedure를 호출하기 위해 CallableStatement객체를 생성한다.
close()
- 현재 커넥션 객체에 할당된 시스템 리소스를 즉시 반환한다.
'develop > Backend -Java' 카테고리의 다른 글
비동기 처리를 위한 Webflux (with. FCM) (0) | 2023.12.09 |
---|---|
[spring] 에러 코드 관리 (0) | 2022.11.25 |
스프링 - jwt (0) | 2022.11.20 |
jwt (json wep token) (0) | 2022.11.20 |