Conexion a Base de datos
/*
* Clase donde esta la conexion a la base de datos
*/
package com.dbmysql.conexion;
//apis
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
/**
*
* @author jose
* Fecha Junio 17 de 2012
*
*/
public class BasedeDatos {
//variabes
private static Connection singleConn;
private static String stJDBCDiver;
private static String stJDBCConnUrl;
private static String stDBUserName;
private static String stDBPassword;
private BasedeDatos() {
}
/*
* Metodo donde se inicializa la base de datos
* Este metodo tiene como parametros el driver la conexion a la base de datos
* el loguin y el password
*
*/
public static void inicializarBasedeDatos(String JDBCDiver, String JDBCConnUrl,
String DBUserName, String DBPassword) {
stJDBCDiver = JDBCDiver; // drivers
stJDBCConnUrl = JDBCConnUrl; //direccion url
stDBUserName = DBUserName; //usuario
stDBPassword = DBPassword; // contraseña
}
/*
* Metodo donde realiza la conexion a la base de datos y retorna una variable
*/
public static Connection getConexion() throws Exception {
if (singleConn == null) {
try {
Class.forName(stJDBCDiver);
} catch (java.lang.ClassNotFoundException e) {
throw new Exception("ClassNotFoundException - " + e.getMessage());
} catch (Exception ex) {
throw ex;
}
try {
singleConn = DriverManager.getConnection(stJDBCConnUrl, stDBUserName, stDBPassword);
JOptionPane.showMessageDialog(null,"Base de datos conectada : " + singleConn);
singleConn.setAutoCommit(false);
} catch (SQLException sqle) {
throw new Exception("SQL Exception - " + sqle.getMessage());
} catch (Exception ex2) {
throw ex2;
//JOptionPane.showMessageDialog(null,"Error de conexion : " + ex2);
}
}
return singleConn;
}
}
Se realiza otra calse para iniciar la conexion
public class DBMySql {
public static void main(String[] args) throws Exception {
BasedeDatos.inicializarBasedeDatos("com.mysql.jdbc.Driver",
"jdbc:mysql://localhost/prueba", "root", "12345");
}
}
No hay comentarios:
Publicar un comentario