How to Retrieve MySQL Database "Schema" Names Using Java JDBC
In Java, the getSchemas() method of the DatabaseMetaData class is typically used to obtain a list of database schemas. However, when working with MySQL, you should instead utilize the getCatalogs() method.
The DatabaseMetaData interface provides various methods for accessing metadata about the database, including the structure, types, and constraints of tables, columns, and indexes. The getCatalogs() method specifically retrieves the names of the database schemas, which correspond to the "Schema" column in the JDBC result set.
Here's an example code snippet that demonstrates how to use getCatalogs() to retrieve a list of database schemas in MySQL:
<code class="java">Class.forName("com.mysql.jdbc.Driver"); // Replace "user" and "password" with your MySQL credentials Connection con = DriverManager.getConnection(connectionURL, "user", "password"); ResultSet rs = con.getMetaData().getCatalogs(); while (rs.next()) { System.out.println("TABLE_CAT = " + rs.getString("TABLE_CAT")); }</code>
This code establishes a connection to the MySQL database, using the specified connectionURL, username, and password. It then retrieves the metadata for the database using the getMetaData() method. The next step involves calling getCatalogs() to retrieve a result set containing the names of the database schemas. Finally, the while loop iterates through the result set, printing the name of each database schema to the console.
The above is the detailed content of How to Retrieve MySQL Database \"Schema\" Names Using Java JDBC?. For more information, please follow other related articles on the PHP Chinese website!