To work with different database schemas in a JDBC application, you can follow the steps below:
1. Establish a connection to the database: To work with a database schema, you first need to establish a connection to the database instance, specifying the database name and login credentials.
Example:
String dbURL = "jdbc:mysql://localhost:3306/mydatabase";
String username = "myusername";
String password = "mypassword";
Connection conn = DriverManager.getConnection(dbURL, username, password);
2. Set the current schema: Once you have established the connection, you can set the current schema using the ‘SET SCHEMA‘ statement.
Example:
Statement stmt = conn.createStatement();
String schema = "myotherdatabase";
stmt.execute("SET SCHEMA " + schema);
3. Execute SQL statements: After setting the current schema, you can execute SQL statements on the database using a ‘Statement‘ or ‘PreparedStatement‘ object.
Example:
PreparedStatement ps = conn.prepareStatement("SELECT * FROM mytable WHERE column = ?");
ps.setString(1, "myvalue");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
// Process the results
}
Note: If you want to work with multiple schemas within the same application, you can create multiple connections, each of which is associated with a different schema. Alternatively, you can use a connection pool that supports multi-tenancy and can handle connections to multiple schemas.