Database Connection
A database connection represents an active link between your Java program and a specific database, established using JDBC, through which queries and commands can be sent.
1. What is a Database Connection?
A database connection represents an active link between your Java program and a specific database, established using JDBC, through which queries and commands can be sent.
2. Why is it used?
Before any data can be read from or written to a database, a valid connection must be created first — it's the foundation on which all further database operations depend.
3. Real-Life Example
Think of dialing a phone call before you can actually speak to someone. The database connection is like that established call — without it, no conversation (data exchange) with the database can happen.
4. Syntax
javaConnection conn = DriverManager.getConnection(url, username, password);
5. Example Program
javaimport java.sql.*; public class ConnectionDemo { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/schooldb"; try (Connection conn = DriverManager.getConnection(url, "root", "password")) { System.out.println("Connected to schooldb successfully!"); } catch (SQLException e) { System.out.println("Connection error: " + e.getMessage()); } } }
Output:
Connected to schooldb successfully!6. Key Points to Remember
- A connection should always be closed once you're done, either manually or using try-with-resources, as shown above.
- Connection details (URL, username, password) should be kept secure and are often stored outside the source code in real projects.
- A failed connection usually throws a
SQLException, which should always be handled properly.