Java 로 DBMS 실행하기

Jan 19, 2024
Java 로 DBMS 실행하기
 

1. 라이브러리 설치

 
 
// https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client implementation group: 'org.mariadb.jdbc', name: 'mariadb-java-client', version: '3.3.2'
 
 
notion image
 
build.gradle - dependencies 에 붙여넣고 오른쪽 상단 코끼리 버튼을 누른다.
 
 
notion image
 
라이브러리에서 mariadb 를 확인할 수 있다.
 
notion image
 
heidiSQL 툴로 테이블을 생성했다.
 
 

2. Java 와 DBMS 연결

 
MariaDB 프로토콜
private static final String DB_URL = "jdbc:mariadb://아이피입력:3306/db명";
 
데이터베이스에 연결을 위해 IP, 포트, 아이디, 패스워드, 프로토콜이 필요하다.
 
public class DBConnection { public static Connection getInstance(){ // Connection은 소켓 String username = "root"; //ID String password = "1234"; //패스워드 String url = "jdbc:mariadb://localhost:3306/cosdb"; // 프로토콜에 IP와 포트가 포함되어 있다. try { Connection conn = DriverManager.getConnection(url,username,password); // conn 프로토콜이 적용된 소켓 System.out.println("db connect success"); return conn; } catch (Exception e) { throw new RuntimeException(e); } } }
 
 
DriverManager 는 라이브러리로 소켓과 연결을 도와준다. conn 은 프로토콜이 적용된 소켓이다.
 
테스트 패키지를 만들어 실행시키면 연결이 된다.
 
notion image
 
💡
테스트 폴더에 import org.junit.jupiter.api.Test; 가 임포트 되어 있으면@Test 를 사용할 수 있다. @Test 는 main 클래스가 없어도 실행할 수 있게 해준다. 이 @** 을 어노테이션(Annotation) 이라고 한다
 
 
테스트 패키지 코드
public class DBConnectionTest { @Test public void getInstance_test(){ String username = "root"; String password = "1234"; String url = "jdbc:mariadb://localhost:3306/cosdb"; try { Connection conn = DriverManager.getConnection(url,username,password); // conn 프로토콜이 적용된 소켓 System.out.println("db connect success"); } catch (Exception e) { throw new RuntimeException(e); } } }
 

3. 쿼리문 전송하기

 
public class BankApp { public static void main(String[] args) { Connection conn = DBConnection.getInstance(); try { PreparedStatement pstmt = conn.prepareStatement("insert into account_tb(password,balance,created_at) values(?,?,now())"); // pstmt.setString(1,"1234") ; int num = pstmt.executeUpdate(); System.out.println(num); } catch (Exception e) { throw new RuntimeException(e); } } }
 
Connection 은 데이터베이스와 연결할 수 있는 인터페이스이고, PreparedStatement는 SQL 문을 데이터베이스로 보내기 전에 먼저 컴파일을 위해 사용한다.
 
쿼리문
insert into account_tb(password,balance,created_at) values(?,?,now())")
values 에 변수를 ? 로 두면 동적으로 값을 입력할 수 있다.
pstmt.setString(1,"1234") ; pstmt.setInt(2,1000);
 
 
() 내부에 넣을 값 : 순서에 넣을 값. 1 부터 시작한다. 코드는 1번 password 는 1234, balance 2번에는 1000을 입력했다.
executeUpdate() 는 데이터베이스의 수정(Insert, Delete , Update) 를 이용할 때 사용하며, 변경된 행의 개수를 반환한다.
 
notion image
 
하나의 테이블을 변경했기 때문에 1 을 반환 받았다.
 
notion image
 
heidiSQL 에서 테이블을 조회하면 추가된 값이 조회된다. 여러번 실행해서 값이 여러 개로 나온다.
Share article
RSSPowered by inblog