English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java 기본 튜토리얼

Java 흐름 제어

Java 배열

Java 지향형 객체(I)

Java 지향형 객체(II)

Java 지향형 객체(III)

Java 예외 처리

Java 목록(List)

Java Queue(큐)

Java Map集合

Java Set集合

Java 입력출력(I/O)

Java Reader/Writer

Java 다른 주제

Java MySQL 연결

이 장에서는 Java가 JDBC를 사용하여 MySQL 데이터베이스에 연결하는 방법을 소개합니다。

Java가 MySQL에 연결할 때는 드라이버 패키지가 필요하며, 최신 버전 다운로드 주소는 다음과 같습니다:http://dev.mysql.com/downloads/connector/j/، 압축을 풀면 jar 라이브러리 파일을 얻고 해당 프로젝트에 이 라이브러리 파일을 가져옵니다。

이 사이트에서 제공하는 jar 패키지를 다운로드할 수 있습니다:mysql-connector-java-5.1.39-bin.jar

이 예제에서 사용하는 것은 Eclipse입니다. jar 패키지를 가져옵니다:

MySQL 8.0 이상 버전의 데이터베이스 연결은 다릅니다:

  • 1、MySQL 8.0 이상 버전의 드라이버 패키지 버전 mysql-connector-java-8.0.16.jar

  • 2、com.mysql.jdbc.Driver com.mysql.cj.jdbc.Driver로 변경합니다。

  • MySQL 8.0 이상 버전은 SSL 연결을 설정하지 않아도 됩니다. 필요시 명시적으로 닫아야 합니다。

  • allowPublicKeyRetrieval=true 클라이언트가 서버에서 공개 키를 가져올 수 있도록 허용합니다。

  • 끝에서 CST를 설정해야 합니다。

드라이버를 로드하고 데이터베이스 연결 방식은 다음과 같습니다:

Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql:")//localhost:3306/test_demo?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC","root","password");

테스트 데이터 생성

다음으로 MySQL에서 w3codebox 데이터베이스를 생성하고 websites 데이터 테이블을 생성하면 다음과 같은 구조가 됩니다:

CREATE TABLE `websites` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(20) NOT NULL DEFAULT '' COMMENT '사이트 이름',
  `url` varchar(255) NOT NULL DEFAULT '',
  `alexa` int(11) NOT NULL DEFAULT '0' COMMENT 'Alexa 순위',
  `country` char(10) NOT NULL DEFAULT '' COMMENT '국가',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

데이터를 추가합니다:

INSERT INTO `websites` VALUES ('1', 'Google', 'https://www.google.cm/', ''1', 'USA'), ('2', '淘宝', 'https://www.taobao.com/', ''13', 'CN'), ('3', 'w3codebox//ko.oldtoolbag.com5892', ''), ('4', '微博', 'http://weibo.com/', ''20', 'CN'), ('5', 'Facebook', 'https://www.facebook.com/', ''3', 'USA');

데이터 테이블은 다음과 같이 표시됩니다:

데이터베이스 연결

아래 예제는 JDBC를 사용하여 MySQL 데이터베이스에 연결되었으며, 사용자 이름, 비밀번호와 같은 일부 데이터는 개발 환경에 따라 설정해야 합니다:

package com.w3codebox.test;
 
import java.sql.*;
 
public class MySQLDemo {
 
    // MySQL 8.0 버전 - JDBC 드라이버 이름 및 데이터베이스 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/w3codebox";
 
    // MySQL 8.0 이상 버전 - JDBC 드라이버 이름 및 데이터베이스 URL
    //static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";  
    //static final String DB_URL = "jdbc:mysql://localhost:3306/w3codebox?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
 
 
    // 데이터베이스의 사용자 이름과 비밀번호는 자신의 설정에 따라야 합니다
    static final String USER = "root";
    static final String PASS = "123456";
 
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try{
            // JDBC 드라이버 등록
            Class.forName(JDBC_DRIVER);
        
            // 연결 열기
            System.out.println("데이터베이스에 연결...");
            conn = DriverManager.getConnection(DB_URL,USER,PASS);
        
            // 쿼리 실행
            System.out.println(" Statement 객체를 예시화...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT id, name, url FROM websites";
            ResultSet rs = stmt.executeQuery(sql);
        
            // 결과 집합 데이터베이스를 펼치기
            while(rs.next()){
                // 필드를 통해 검색
                int id  = rs.getInt("id");
                String name = rs.getString("name");
                String url = rs.getString("url");
    
                // 출력 데이터
                System.out.print("ID: " + id);
                System.out.print(", 지점 이름: " + name);
                System.out.print(", 사이트 URL: "" + url);
                System.out.print("\n");
            }
            // 작업이 완료되면 닫습니다
            rs.close();
            stmt.close();
            conn.close();
        }catch(SQLException se){
            // JDBC 오류 처리
            se.printStackTrace();
        }
            // Class.forName 오류 처리
            e.printStackTrace();
        }
            // 자원을 닫습니다
            try{
                if(stmt!=null) stmt.close();
            }2{
            }// 아무것도 하지 않습니다
            try{
                if(conn!=null) conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }
}

위 예제 실행 결과는 다음과 같습니다: