File Handling & JDBC · Lesson 111 of 150
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.
01What 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.
02Why 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.
03Real-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.
04Syntax
javaimport java.sql.*; Connection conn = DriverManager.getConnection(url, username, password);
05Example 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.)
06Key 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.