[Java] 90. JDBC 연결 테스트

백하림's avatar
Mar 05, 2025
[Java] 90. JDBC 연결 테스트
notion image

1. 더미 데이터 세팅

-- root로 접속한다. -- DB를 생성한다. create database store; -- store디비를 선택한다. use store; CREATE TABLE store_tb( id int primary key auto_increment, name varchar(20), price int, qty int ); insert into store_tb(name, price, qty) values('사과', 1000, 50); insert into store_tb(name, price, qty) values('딸기', 2000, 50); commit;

2. 자바 프로젝트 생성

1. File - New - Project 클릭

notion image
💡
  1. 2. Name : store
  1. Build system : Gradle
  1. Gradle DSL : Groovy
notion image

2. 구글에 MVN REPOSITORY 검색 → 검색창에 mysql 검색 → 1. MySQL Connector/J 클릭

notion image

3. 자신의 버전에 맞는 것을 클릭 (난 8.0.33)

notion image

4. Gradle 선택 후 아래 글 복사

notion image

5. 인텔리J로 돌아와서 build.gradle 선택 → dependencies에 붙여넣기

notion image

3. DB 연결 테스트

import java.sql.Connection; import java.sql.DriverManager; public class DBConnection { public static Connection getConnection() { String url = "jdbc:mysql://localhost:3306/store"; String username = "root"; String password = "bitc5600!"; try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection(url,username,password); return conn; } catch (Exception e) { throw new RuntimeException(e); } } }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class storeApp { public static void main(String[] args) { // 1. DB 연결 - 세션 만들어짐 Connection conn = DBConnection.getConnection(); // 2. 버퍼 try { // 세미콜론 붙이면 안 됨 물음표는 1번부터 시작 String sql = "select id, name, price, qty from store_tb where id = ?"; PreparedStatement psmt = conn.prepareStatement(sql); psmt.setInt(1, 1); // 1번 물음표, 참조할 ID, 현재 ID는 2번까지만 있는 상태 // ID 3번 이상을 조회할 경우 false // 3. flush (rs = table 조회 결과! 즉 view) ResultSet rs = psmt.executeQuery(); boolean isThere = rs.next(); // 커서 한 칸 내리기 !중요! System.out.println("isThere : " + isThere); if (isThere) { int id = rs.getInt("id"); String name = rs.getString("name"); int price = rs.getInt("price"); int qty = rs.getInt("qty"); System.out.println(id + " " + name + " " + price + " " + qty); } } catch (SQLException e) { throw new RuntimeException(e); } } }
next는 boolean 타입 true이면 값을 반환
next는 boolean 타입 true이면 값을 반환
false이면 반환 x
false이면 반환 x

4. 만약 한글이 깨진다면 Settings → gradle 검색 → Build, Execution, Depolyment의 Gradle 클릭 → Gradle Projects에서 Build and run using과 Run tests using을 인텔리J로 바꿈

notion image
Share article

harimmon