Home >Database >Mysql Tutorial >How to Create a MySQL Database from Java Without Specifying the Database Name in the JDBC URL?

How to Create a MySQL Database from Java Without Specifying the Database Name in the JDBC URL?

Susan Sarandon
Susan SarandonOriginal
2024-11-30 11:59:14107browse

How to Create a MySQL Database from Java Without Specifying the Database Name in the JDBC URL?

Creating a MySQL Database from Java Without Database Specification in JDBC URL

It's possible to create a MySQL database from Java even when the database name is not specified in the JDBC URL. Here's how to do it:

  1. Establish a connection to the MySQL server using a URL that doesn't include the database name:
String url = "jdbc:mysql://localhost:3306/?user=root&password=rootpassword";
Connection con = DriverManager.getConnection(url);
  1. Create a Statement object to execute the SQL query:
Statement s = con.createStatement();
  1. Execute the SQL query to create the database:
int result = s.executeUpdate("CREATE DATABASE databasename");
  1. Check the value of result to verify if the database was created successfully. A non-zero value indicates success.
  2. Close the Statement and Connection objects to release resources:
s.close();
con.close();

By following these steps, you can create a MySQL database in Java even without specifying the database name in the JDBC URL.

The above is the detailed content of How to Create a MySQL Database from Java Without Specifying the Database Name in the JDBC URL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn