Lecture 5: Connecting Java and Database
Complete Connection Code:
import [Link].*;
public class DemoJdbc {
public static void main(String[] args) {
// Database connection parameters
String url = "jdbc:postgresql://localhost:5432/demo";
String username = "postgres";
String password = "0000"; // Your PostgreSQL password
Connection conn = null;
try {
// Step 1: Load and register driver
[Link]("[Link]");
[Link]("Driver loaded successfully");
// Step 2: Create connection
conn = [Link](url, username, password);
[Link]("Connection established successfully");
} catch (ClassNotFoundException e) {
[Link]("Driver not found: " + [Link]());
} catch (SQLException e) {
[Link]("Connection failed: " + [Link]());
} finally {
// Step 3: Close connection
try {
if (conn != null && ![Link]()) {
[Link]();
[Link]("Connection closed");
}
} catch (SQLException e) {
[Link]("Error closing connection: " + [Link]());
}
}
}
}
Connection URL Format:
jdbc:postgresql://hostname:port/database_name
● hostname: Server address (localhost for local machine)
● port: PostgreSQL port (default: 5432)
● database_name: Name of your database
Common Connection Issues:
1. Driver not found:Ensure JDBC driver is in the classpath.
2. Connection refused:Check if PostgreSQL service is running
3. Authentication failed:Verify username/password
4. Database not found:Ensure database exists