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

Java JDBC · Intermediate · question 22 of 100

What is the role of Java.sql.Connection interface in JDBC?

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

The java.sql.Connection interface is a fundamental component of JDBC. It represents a connection between a Java program and a database.

The Connection interface provides methods to establish a connection with a specific database and manage it. It allows you to submit SQL statements and queries, and retrieve results. It also enables you to commit and roll back transactions, set transaction isolation levels, and manage connections, among other things.

Here’s an example of how to establish a connection using JDBC:

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class Example {
        public static void main(String[] args) {
            Connection conn = null;
            try {
                // Register the JDBC driver
                Class.forName("com.mysql.jdbc.Driver");
                
                // Open a connection
                String url = "jdbc:mysql://localhost/coffeeDB";
                String user = "root";
                String password = "password";
                conn = DriverManager.getConnection(url, user, password);
                
                // Do something with the connection
                
                // Close the connection
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (conn != null) {
                        conn.close();
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

In this example, we first register the MySQL JDBC driver using ‘Class.forName()‘. Then, we create a connection to a local MySQL database using ‘DriverManager.getConnection()‘, passing the database URL, username, and password as parameters. We can then perform various operations on the database using this connection. Finally, we close the connection using ‘conn.close()‘.

In summary, the Connection interface in JDBC provides a way to connect to a database, manage the connection, and perform various operations on the database.

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