Create a database in MySQL from Java?

MySQLMySQLi Database

The following is the code to create a database in MySQL from Java. We are creating the database with name, “Customer_Tracker_Database”

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class CreateDatabaseDemo {
   public static void main(String[] args) {
      Connection con=null;
      Statement stmt=null;
      String yourDatabaseName="Customer_Tracker_Database";
      try {
         con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test3?useSSL=false",
         "root","123456");
         stmt = con.createStatement();
         int status = stmt.executeUpdate("CREATE DATABASE "+yourDatabaseName);
         if(status > 0) {
            System.out.println("Database is created successfully !!!");
         }
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
}

The following is the output

Database is created successfully !!!

Here is the snapshot of the sample output

Now let us check the database ‘Customer_Tracker_Database’ is created or not.

The query is as follows

mysql> show databases;

The following is the output

Look at the sample output above, the database is created successfully.
raja
Published on 29-Mar-2019 11:15:28
Advertisements