DEV Community

Shelner
Shelner

Posted on

Explanation of `Connection`, `DriverManager` and `SQLExeption` in Java

1. Connection

  • Represents a live connection to your database
  • You use it to:
    • execute SQL (SELECT, INSERT, etc.)
    • manage transactions (commit, rollback) Think of it as: a session between your Java app and the DB.

A connection (session) with specific database. SQL statements are executed and results are returned within the context of a connection.

2. DriverManager

  • Responsible for creating the Connection
  • It:
    • finds the correct JDBC driver (e.g., MySQL)
    • opens the connection using URL, USER, PASSWORD Think of it as: a factory that gives you a Connection.

3. SQLExeption

  • An exception (error) thrown when something goes wrong with the database.
  • Exampls:
    • wrong password
    • database not running
    • invalid SQL query Think of it as: a signal that DB operation failed

How they work together

Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Enter fullscreen mode Exit fullscreen mode
  • DriverManager -> tries to connect
  • If success -> returns a Connection
  • If failure -> throws SQLException
DriverManager -> creates -> Connection -> used for DB work
                           ↑
                     may throw SQL Exception
Enter fullscreen mode Exit fullscreen mode

Top comments (0)