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

JDBC_Connection_Example

The document provides a Java program that demonstrates how to connect to a MySQL database using JDBC. It includes the necessary imports, database connection details, and error handling for connection issues. The program outputs messages indicating the success or failure of the connection and ensures the connection is closed properly.

Uploaded by

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

JDBC_Connection_Example

The document provides a Java program that demonstrates how to connect to a MySQL database using JDBC. It includes the necessary imports, database connection details, and error handling for connection issues. The program outputs messages indicating the success or failure of the connection and ensures the connection is closed properly.

Uploaded by

sankarayaswitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Java Program to Connect to Database

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

public class JDBCConnectionExample {

public static void main(String[] args) {


// Database URL, username, and password
String jdbcURL = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "your_password"; // change this to your actual
password

Connection connection = null;

try {
// Load MySQL JDBC driver (optional in modern Java, but good
practice)
Class.forName("com.mysql.cj.jdbc.Driver");

// Connect to the database


connection = DriverManager.getConnection(jdbcURL, username,
password);
System.out.println("Connection successful!");

} catch (ClassNotFoundException e) {
System.out.println("MySQL JDBC Driver not found.");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Connection failed. Check output
console.");
e.printStackTrace();
} finally {
// Close the connection
try {
if (connection != null && !connection.isClosed()) {
connection.close();
System.out.println("Connection closed.");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}

Output:

Connection successful!

Connection closed.

You might also like