0% found this document useful (0 votes)
3 views2 pages

Connecting Java and DB

The document provides a complete Java code example for connecting to a PostgreSQL database using JDBC. It outlines the necessary steps including loading the driver, establishing the connection, and closing the connection, along with common connection issues and their solutions. The connection URL format is also specified for clarity on parameters such as hostname, port, and database name.

Uploaded by

radhav142000
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Connecting Java and DB

The document provides a complete Java code example for connecting to a PostgreSQL database using JDBC. It outlines the necessary steps including loading the driver, establishing the connection, and closing the connection, along with common connection issues and their solutions. The connection URL format is also specified for clarity on parameters such as hostname, port, and database name.

Uploaded by

radhav142000
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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

You might also like