Computer >> 컴퓨터 >  >> 프로그래밍 >> MySQL

JDBC API로 MySQL 데이터베이스 생성하는 방법 완벽 가이드

일반적으로 CREATE DATABASE 쿼리를 사용하면 간단하게 데이터베이스를 생성할 수 있습니다.

기본 문법

CREATE DATABASE DatabaseName;

JDBC API를 사용하여 데이터베이스를 생성하려면 아래의 네 가지 단계를 순서대로 수행해야 합니다.

1. 드라이버 등록

DriverManager 클래스의 registerDriver() 메서드를 사용하여 드라이버 클래스를 등록합니다. 이때 매개변수로 드라이버 클래스 이름을 전달합니다.

2. 데이터베이스 연결 설정

DriverManager 클래스의 getConnection() 메서드를 사용하여 데이터베이스에 연결합니다. URL(String), 사용자 이름(String), 비밀번호(String)를 매개변수로 전달합니다.

3. Statement 객체 생성

Connection 인터페이스의 createStatement() 메서드를 사용하여 SQL 쿼리를 실행할 Statement 객체를 생성합니다.

4. 쿼리 실행

Statement 인터페이스의 execute() 메서드를 사용하여 데이터베이스 생성 쿼리를 실행합니다.

전체 예제 코드

다음 JDBC 프로그램은 MySQL 서버에 연결한 후 mydatabase라는 이름의 데이터베이스를 생성합니다.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateDatabaseExample {
   public static void main(String args[]) throws SQLException {
      // 드라이버 등록
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      // 연결 설정
      String mysqlUrl = "jdbc:mysql://localhost/";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      // Statement 객체 생성
      Statement stmt = con.createStatement();
      // 데이터베이스 생성 쿼리
      String query = "CREATE database MyDatabase";
      // 쿼리 실행
      stmt.execute(query);
      System.out.println("Database created");
   }
}

실행 결과

Connection established......
Database created......

생성된 데이터베이스 확인하기

MySQL에서는 show databases 명령어로 현재 서버에 존재하는 모든 데이터베이스 목록을 조회할 수 있습니다. 이 명령어를 실행하면 방금 생성한 데이터베이스가 목록에 포함되어 있는지 확인할 수 있습니다.

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| base               |
| details            |
| exampledatabase    |
| logging            |
| mydatabase         |
| mydb               |
| mysql              |
| performance_schema |
| students           |
| sys                |
| world              |
+--------------------+
12 rows in set (0.00 sec)

위 출력 결과에서 mydatabase가 목록에 정상적으로 추가된 것을 확인할 수 있습니다. 참고로 최신 MySQL 환경에서는 구형 com.mysql.jdbc.Driver 대신 com.mysql.cj.jdbc.Driver 클래스를 사용하는 것이 권장됩니다.