JDBC
JDBC (Java Database Connectivity) is an API that allows a Java program to connect to and interact with a relational database, like MySQL or PostgreSQL, to run queries and manage data.
1. What is JDBC?
JDBC (Java Database Connectivity) is an API that allows a Java program to connect to and interact with a relational database, like MySQL or PostgreSQL, to run queries and manage data.
2. Why is it used?
Most real applications need to store and retrieve data from a database. JDBC provides a standard way for Java code to talk to different databases, without needing completely different code for each database type.
3. Real-Life Example
Think of a universal translator that lets you communicate with people speaking different languages, using one consistent method of translation. JDBC lets Java communicate with different databases using one consistent approach.
4. Syntax
javaimport java.sql.*; Connection conn = DriverManager.getConnection(url, username, password);
5. Example Program
javaimport java.sql.*; public class JdbcDemo { public static void main(String[] args) { try { Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mydb", "root", "password" ); System.out.println("Database connected successfully!"); conn.close(); } catch (SQLException e) { System.out.println("Connection failed: " + e.getMessage()); } } }
Output:
Database connected successfully!(Actual output depends on whether a real database with matching credentials is available.)
6. Key Points to Remember
- JDBC requires a database-specific driver (like MySQL Connector/J) to actually connect to that database.
- The connection URL typically includes the database type, host, port, and database name.
- Always close database connections properly once done, to avoid wasting resources.