Skip to content

Instantly share code, notes, and snippets.

@inazense
Created February 14, 2018 02:39
Show Gist options
  • Save inazense/8334c53e17f8992ca5f16f0ad63b9a59 to your computer and use it in GitHub Desktop.
Save inazense/8334c53e17f8992ca5f16f0ad63b9a59 to your computer and use it in GitHub Desktop.
Clase usada para generar un objeto Connection a base de datos MySQL siguiendo el patrón Singleton
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConexionSingleton {
// Propiedades
private static Connection CONEXION = null;
// Constructor
private ConexionSingleton() {
String url = "jdbc:mysql://localhost:3306/test";
String driver = "com.mysql.jdbc.Driver";
String usuario = "root";
String password = "";
try {
Class.forName(driver);
CONEXION = DriverManager.getConnection(url, usuario, password);
}
catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
// Métodos
/**
* Devuelve la conexión a la base de datos
* @return Un objeto Connection único para toda la aplicación
*/
public static Connection devolverConexion() {
if (CONEXION == null) {
new ConexionSingleton();
}
return CONEXION;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment