0% found this document useful (0 votes)
2 views

ConnectionScript

The document contains a Java class named 'Database' that manages connections to a MySQL database for a chat application. It includes methods to connect and disconnect from the database, handling exceptions appropriately. The main method demonstrates connecting to and disconnecting from the database using these methods.

Uploaded by

megatuty65
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)
2 views

ConnectionScript

The document contains a Java class named 'Database' that manages connections to a MySQL database for a chat application. It includes methods to connect and disconnect from the database, handling exceptions appropriately. The main method demonstrates connecting to and disconnecting from the database using these methods.

Uploaded by

megatuty65
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
You are on page 1/ 1

package Hello;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Database {


private static final String URL = "jdbc:mysql://localhost:3306/chatapp";
private static final String USER = "root";
private static final String PASSWORD = "";
private static Connection connection;

public static Connection connect() {


try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(URL, USER, PASSWORD);
System.out.println("Connected to the database!");
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Failed to connect to the database!");
e.printStackTrace();
}
return connection;
}

public static void disconnect() {


try {
if (connection != null && !connection.isClosed()) {
connection.close();
System.out.println("Disconnected from the database!");
}
} catch (SQLException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {


Connection conn = Database.connect();
Database.disconnect();
}
}

You might also like