0% found this document useful (0 votes)
8 views1 page

Java Database Connection Example

The document contains a Java class named DatabaseConnection that manages a connection to a MySQL database. It includes methods to establish and close the connection, handling SQL exceptions appropriately. The class uses a singleton pattern to ensure only one connection instance is created.

Uploaded by

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

Java Database Connection Example

The document contains a Java class named DatabaseConnection that manages a connection to a MySQL database. It includes methods to establish and close the connection, handling SQL exceptions appropriately. The class uses a singleton pattern to ensure only one connection instance is created.

Uploaded by

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

import [Link].

Connection;
import [Link];
import [Link];

public class DatabaseConnection {


private static final String URL = "jdbc:mysql://localhost:3306/cafe_manager";
private static final String USER = "root"; // Replace with your MySQL username
private static final String PASSWORD = ""; // Replace with your MySQL password
private static Connection connection = null;

public static Connection getConnection() {


if (connection == null) {
try {
connection = [Link](URL, USER, PASSWORD);
[Link]("Database connected successfully.");
} catch (SQLException e) {
[Link]("Failed to connect to database: " +
[Link]());
}
}
return connection;
}

public static void closeConnection() {


if (connection != null) {
try {
[Link]();
connection = null;
[Link]("Database connection closed.");
} catch (SQLException e) {
[Link]("Error closing connection: " + [Link]());
}
}
}
}

You might also like