How to create a database in MySQL using a JDBC API?

A. In general, you can create a database using the CREATE DATABASE query.



To create a Database using JDBC API you need to:

  • Register the driver: Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter.

  • Establish a connection: Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it.

  • Create Statement: Create a Statement object using the createStatement() method of the Connection interface.

  • Execute the Query: Execute the query using the execute() method of the Statement interface.


Following JDBC program establishes connection with MySQL and creates a database named 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 {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();
      //Query to create a database
      String query = "CREATE database MyDatabase";
      //Executing the query
      System.out.println("Database created");


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

The show databases command gives you the list of databases in MySQL. If you verify the list of databases using this command, you can see the newly created database as:

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)

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started