WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java JDBC · Advanced · question 47 of 100

How do you work with different database schemas in a JDBC application?

📕 Buy this interview preparation book: 100 Java JDBC questions & answers — PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java JDBC interview — then scores it.
📞 Practice Java JDBC — free 15 min
📕 Buy this interview preparation book: 100 Java JDBC questions & answers — PDF + EPUB for $5

All 100 Java JDBC questions · All topics