JDBC
[JDBC] 이클립스와 MySQL 연동
jane.dev
2021. 7. 24. 19:18
반응형
2021.07.24 - [Java] - [Java] Mac 자바 JDBC - 이클립스와 MySQL, Oracle 연동
[Java] Mac 자바 JDBC - 이클립스와 MySQL, Oracle 연동
JDBC(Java DataBase Connectivity) 자바에서 데이터베이스에 접속, 질의, 데이터 조작을 할 수 있도록 제공하는 자바 API JDBC 를 사용하려면 .jar 파일이 필요 MySQL https://dev.mysql.com/downloads/file/?id=4..
wheneveryouwantsz.tistory.com
데이터베이스와 연동 코드작성
1. 패키지 아래 코드 작성
import java.sql.*;
2. Main method 내부에 작성
Connection con = null; // 연결은 java.sql의 인터페이스 Connection 객체로 진행
Statement stmt = null; // 쿼리문을 저장하고 실행하기 위한 구문 객체 생성
ResultSet rs = null; // SELECT 구문의 반환데이터를 받음
// SELECT 구문이 아니면 작성하지 않음
try{
// 클래스의 위치를 알려줌, 밴더사 마다 이름이 다름
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/데이터베이스명";
// con 변수에 정보 저장
con = DriverManager.getConnection(url, "계정명", "비밀번호");
// 쿼리를 실행, 계정명과 비밀번호가 저장된 con의 정보를 stmt에 저장
stmt = con.createStatement();
// 쿼리작성, 쿼리문 마지막 세미콜론(;) 생략
String sql = "SELECT * FROM 테이블명";
// 쿼리를 작성하고 stmt의 파라미터로 제공, 수행한 쿼리의 반환데이터는 rs 변수에 저장
rs = stmt.executeQuery(sql)
// 쿼리가 SELECT 구문이 아니면 아래처럼 작성
rs = stmt.executeUpdate(sql);
rs.next();
}catch(ClassNotFoundException e){
System.out.println("드라이버 로딩 실패");
}catch(SQLException e){
System.out.println("에러: " + e);
}finally{
try{
if(con != null && !con.isClosed()){
con.close();
}
}catch(SQLException e){
e.printStackTrace();
}
}
rs는 커서(Cursor)라는 개념을 사용하며 인덱스가 0 이전부터 시작해서 SELECT 구문의 Row 개수만큼 길이가 생성됨
커서를 다음으로 옮기는 방법: rs.next(); - 커서를 옮기면서 다음 Row에 데이터가 있으면 True, 없으면 False를 반환
예제)
Row 4개의 테이블 생성
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/testDB";
con = DriverManager.getConnection(url, "root", "(root의 비밀번호)");
stmt = con.createStatement();
String sql = "SELECT * FROM testTbl4";
rs = stmt.executeQuery(sql);
System.out.println(rs.next()); // true
System.out.println(rs.next()); // true
System.out.println(rs.next()); // true
System.out.println(rs.next()); // true
System.out.println(rs.next()); // false
}catch(ClassNotFoundException e) {
System.out.println("드라이버 로딩 실패");
}catch(SQLException e) {
System.out.println("에러: " + e);
}finally {
try {
if(con != null && !con.isClosed()) {
con.close();
}
}catch(SQLException e) {
e.printStackTrace();
}
}
}
데이터 2개 추가
데이터 출력 방법
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/testDB";
con = DriverManager.getConnection(url, "root", "(root의 비밀번호)");
stmt = con.createStatement();
String sql = "SELECT * FROM testTbl4";
rs = stmt.executeQuery(sql);
while(rs.next()) {
System.out.println("Name: " + rs.getString(1) +
", Age: " + rs.getInt(2) +
", Address: " + rs.getString(3));
}
}catch(ClassNotFoundException e) {
System.out.println("드라이버 로딩 실패");
}catch(SQLException e) {
System.out.println("에러: " + e);
}finally {
try {
if(con != null && !con.isClosed()) {
con.close();
}
}catch(SQLException e) {
e.printStackTrace();
}
}
}