본문 바로가기

2023.11.21-2024.05.31

231226 JAVA DB01

package com.sukgi.db;

 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

 

//자바와 데이터베이스 연동합니다

public class DB01 {

public static void main(String[] args) {

Connection conn = null;

PreparedStatement pstmt = null;

ResultSet rs = null;

String db = "jdbc:mariadb://guro.wisejia.com:3308/employees";

String id = "c23c_22";

String pw = "01234567";

String sql = "SELECT * FROM departments";

// 객체 3가지, 클래스 3개로 구별해서 사용

 

try {

Class.forName("org.mariadb.jdbc.Driver");

conn = DriverManager.getConnection(db, id, pw);// 접속정보

pstmt = conn.prepareStatement(sql);// conn에서 만든것을 실행

rs = pstmt.executeQuery();// pstmt가 실행한 최종결과는 rs가 담아요

 

while (rs.next()) {// while이 계속 돈다. rs에 값이 없을때까지

String dept_no = rs.getString("dept_no");

String dept_name = rs.getString("dept_name");

System.out.println(dept_no + ": " + dept_name);

 

}

 

} catch (ClassNotFoundException e) {

System.out.println("해당 클래스가 없습니다.");

} catch (SQLException e) {

System.out.println("접속정보를 확인해주세요.");

} finally {

try {// 마지막에 사용한 것부터 닫아줌

rs.close();

pstmt.close();

conn.close();

} catch (SQLException e) {

 

}

 

}

}

 

}

 

 

d009: Customer Service

d005: Development

d002: Finance

d003: Human Resources

d001: Marketing

d004: Production

d006: Quality Management

d008: Research

d007: Sales

'2023.11.21-2024.05.31' 카테고리의 다른 글

231226 JAVA EmployeesDAO  (1) 2023.12.26
231226 JAVA DBConnection  (0) 2023.12.26
231226 JAVA Exception03  (0) 2023.12.26
231226 JAVA Exception02  (0) 2023.12.26
231226 JAVA Exception01  (1) 2023.12.26