KangMoo
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # JDBC (Java Database Connectivity) ## JDBC란? ![image](https://hackmd.io/_uploads/BkNYFL2b0.png) JDBC(Java Database Connectivity)는 자바 언어를 사용하여 데이터베이스에 접근하고, 데이터를 조회하고 조작할 수 있도록 하는 API(애플리케이션 프로그래밍 인터페이스)이다. JDBC는 자바 언어와 데이터베이스 간의 연결을 제공하며, 데이터베이스와 자바 언어 간의 통신을 위한 표준 인터페이스를 제공한다. JDBC를 사용하면 자바 언어로 데이터베이스 작업을 위해 표준 SQL 문을 사용하며, 다양한 종류의 데이터베이스에 동일한 방법으로 접근할 수 있는 것이 장점이다. JDBC를 사용하려면 드라이버를 로드하고, 데이터베이스에 연결하고, SQL 쿼리를 실행하고, 결과를 처리하는 과정을 거쳐야 한다. ![image](https://hackmd.io/_uploads/ryy7YL3ZR.png) JDBC 드라이버는 데이터베이스와 자바 언어 간의 통신을 위한 중간 계층으로, 데이터베이스와 통신하는 데 필요한 로직을 구현하고, JDBC API를 구현한 클래스 라이브러리이다. JDBC 드라이버는 데이터베이스 제조사에서 제공되며, 데이터베이스 종류에 따라 다양한 드라이버가 존재하며 JDBC 드라이버는 데이터베이스에 연결하고, SQL 쿼리를 실행하며, 결과를 처리하는 역할을 한다. ## JDBC 사용법 ### JDBC 드라이버 다운로드 JDBC를 사용하려면 먼저 JDBC 드라이버를 다운로드하고, 클래스패스에 추가해야 한다. 직접 다운로드하여 사용할 수도 있지만, Maven, Gradle 등의 의존성 관리 도구를 사용하여 의존성을 추가하는 것이 편리하다. 예를 들어 Mysql 데이터베이스를 사용할 경우, 다음과 같이 pom.xml에 의존성을 추가할 수 있다. ```xml <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.3.0</version> </dependency> ``` MariaDB를 사용할 경우, 다음과 같이 의존성을 추가할 수 있다. ```xml <dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <version>3.3.3</version> </dependency> ``` > 당연하지만 버전 정보는 적절하게 적용해야 한다. ### JDBC 드라이버 로드 JDBC 드라이버를 사용하기 위해서는 먼저 드라이버를 로드해야 한다. 드라이버를 로드하는 방법은 다음과 같다. MySQL을 사용하는 경우 ```java Class.forName("com.mysql.cj.jdbc.Driver"); ``` MariaDB를 사용하는 경우 ```java Class.forName("org.mariadb.jdbc.Driver"); ``` ### 데이터베이스 연결 드라이버를 로드한 후, 데이터베이스에 연결한다. `DriverManager.getConnection()` 메서드를 사용하여 데이터베이스에 연결할 수 있다. ```java String url = "jdbc:mysql://localhost:3306/mydb"; Connection conn = DriverManager.getConnection(url, user, password); ``` ### Statement 생성 `Connection` 객체를 사용하여 `Statement` 객체를 생성한다. `Statement` 객체는 SQL 쿼리를 실행하는 데 사용된다. ```java Statement stmt = conn.createStatement(); ``` ### SQL 쿼리 실행 `Statement` 객체를 사용하여 SQL 쿼리를 실행한다. `executeQuery()` 메서드는 SELECT 쿼리를 실행하고, `executeUpdate()` 메서드는 INSERT, UPDATE, DELETE 쿼리를 실행한다. ```java ResultSet rs = stmt.executeQuery("SELECT * FROM Employees WHERE EmployeeID = 1"); ``` ### ResultSet 사용 `ResultSet` 객체를 사용하여 쿼리 실행 결과를 읽고 처리할 수 있다. ```java while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println("id: " + id + ", name: " + name); } ``` ### 자원 해제 데이터베이스 작업이 끝나면 `ResultSet`, `Statement`, `Connection` 객체를 닫아야 한다. ```java rs.close(); stmt.close(); conn.close(); ``` ## 전체 코드 예시 다음은 JDBC를 사용하여 데이터베이스에 연결하고, 데이터를 조회하는 예시 코드이다. ```java import java.sql.*; public class Main { public static void main(String[] args) throws Exception { Class.forName("org.mariadb.jdbc.Driver"); // MySQL의 경우 : com.mysql.cj.jdbc.Driver 사용 try (Connection conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/mydb", "hkm0629", "hkm0629"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM Employees")) { while (rs.next()) { int id = rs.getInt("EmployeeID"); String name = rs.getString("name"); System.out.println("id: " + id + ", name: " + name); } } } } ``` ## JDBC의 한계 JDBC는 데이터베이스에 접근하고 데이터를 조회하는 데 사용되는 강력한 도구이지만, 몇 가지 한계가 있다. 1. **복잡한 코드**: JDBC 코드는 반복적이고 복잡하다. SQL 쿼리를 실행하고 결과를 처리하는 과정이 반복되기 때문에 코드가 길어지고 가독성이 떨어진다. 2. **SQL Injection**: JDBC는 SQL Injection 공격에 취약하다. 사용자 입력을 그대로 SQL 쿼리에 넣으면 보안 문제가 발생할 수 있다. 3. **성능**: JDBC는 데이터베이스와의 연결을 맺고 끊는 과정이 매번 발생하기 때문에 성능이 떨어질 수 있다. 이 때문에 Connection Pool을 사용하여 성능을 향상시키는 방법이 있긴 하지만, 내장된 기능이 아니므로 별도로 구현해야 한다. 최근에는 JDBC를 그대로 사용하는 것보다 ORM(Object-Relational Mapping) 프레임워크를 사용하는 것이 더 효율적이다. 다만, DBMS와 JDBC의 이해 없이 ORM을 사용하게 된다면 트러블슈팅이 어려울 수 있으므로, DBMS와 JDBC에 대한 기본적인 이해를 가지고 사용하는 것이 좋다.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully