xxxxxxxxxx
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
xxxxxxxxxx
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
xxxxxxxxxx
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
public static void main(String[] args) {
// JDBC driver class for MySQL
String driverClass = "com.mysql.jdbc.Driver";
// Database credentials
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
Connection connection = null;
try {
// Load the JDBC driver
Class.forName(driverClass);
// Establish a connection to the database
connection = DriverManager.getConnection(url, username, password);
// Connection successful
System.out.println("Connected to the database!");
// TODO: Use the connection for database operations
// Close the connection
connection.close();
} catch (ClassNotFoundException e) {
System.out.println("Failed to load JDBC driver: " + driverClass);
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Failed to establish connection to the database!");
e.printStackTrace();
} finally {
// Close the connection (in case of any exceptions)
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}