MySqlCreateDatabase.java - Connector/J JDBC Create Database

Q

How to create a new database in MySQL using the Connector/J JDBC driver? I want to see a Java program example.

✍: FYIcenter.com

A

Here is a Java example that shows you how to create a new database in MySQL using the Connector/J JDBC driver:

// Copyright (c) 2016 FYIcenter.com
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;

// Example of sqljdbc JDBC driver to create a new database
public class MySqlCreateDatabase {
   public static void main(String [] args) throws Exception {

      // Connector/J JDBC connection URL with required elements
      String url = "jdbc:mysql://localhost?user=root&password=fyicenter&useSSL=false";
      Connection con = DriverManager.getConnection(url);
      System.out.println("JDBC connection URL: "+url); 
      System.out.println("   Connected to: "+con.getCatalog()); 
      Statement st = con.createStatement();

      // Create a new database "FyiCenter" and connect to it  
      String db = "FyiCenter";      
      st.execute("CREATE DATABASE "+db);
      con.setCatalog(db);
      System.out.println("   Connected to: "+con.getCatalog()); 

      // Can not drop any database, with the old "st",
      // since it was created with the old "con",
      // which has no database selected
      // st.execute("DROP DATABASE "+db);

      // Get a new Statement object in "st" 
      // from the new "con", 
      // which has "FyiCenter" database selected
      st = con.createStatement();
      st.execute("DROP DATABASE "+db);
      
      con.close();
   }
}

You can compile and run the above example in a command window as shown below:

C:\fyicenter>\local\jdk-1.8.0\bin\javac 
   MySqlCreateDatabase.java

C:\fyicenter>\local\jdk-1.8.0\bin\java
   -cp .;C:\local\mysql-connector-java-5.1.40\mysql-connector-java-5.1.40-bin.j
   MySqlCreateDatabase

JDBC connection URL: 
   jdbc:mysql://localhost?user=root&password=fyicenter&useSSL=false
   Connected to:
   Connected to: FyiCenter   

Note that:

  • After calling con.setCatalog(db), you need update Statement objects. Old statement objects are still connecting the old database, or no database.
  • "DROP DATABASE xyz" requires that the statement object is created from a connection with database selected.

 

Examples for Connector/J - JDBC Driver for MySQL

⇒⇒FAQ for Connector/J - JDBC Driver for MySQL

2016-12-02, 1216👍, 0💬