Archivo del sitio

Conectar Base datos MySql con Java[JDBC]

Clase para conectar una base de datos mysql en java, usando la libreria mysql.

Creada en clases de  tópicos avanzado de programación  [By Soma].

/**
*
* @author Soma
*

*
*/
package BD;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class BD {
private String user;
private String password;
private String url;
private String driverClassName;
private Connection conn = null;
private Statement stmt;

public BD(String user, String password, String url, String driverClassName) {
this.user = user;
this.password = password;
this.url = url;
this.driverClassName = driverClassName;
}
public BD()
{
this.user = "root";
this.password="tupass";
this.url = "jdbc:mysql://localhost/tu_basedatos";
this.driverClassName = "com.mysql.jdbc.Driver"; // driver
}
public String getPassword() {
return password;
}

public String getUrl() {
return url;
}

public String getUser() {
return user;
}

public void setPassword(String password) {
this.password = password;
}

public void setUrl(String url) {
this.url = url;
}

public Connection getConn() {
return conn;
}

public void setConn(Connection conn) {
this.conn = conn;
}

public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}

public String getDriverClassName() {
return driverClassName;
}

public void setUser(String user) throws SQLException {
this.user = user;
}

public void conectar() throws SQLException {
try {
Class.forName(this.driverClassName).newInstance();
this.conn = DriverManager.getConnection(this.url, this.user, this.password);

} catch (Exception err) {
System.out.println("Error " + err.getMessage());
}
}

public ResultSet obtenerDatos(String sql) throws SQLException {

this.stmt = conn.createStatement();
return this.stmt.executeQuery(sql);
}

public void actualizar(String sql) throws SQLException {
this.stmt = conn.createStatement();
stmt.executeUpdate(sql);
}
public ResultSet ExeGet(String Q) throws SQLException{
Statement st = this.conn.createStatement();
return (ResultSet) st.executeQuery(Q);
}
public int Exe(String Q) throws SQLException{
Statement st = this.conn.createStatement();
return st.executeUpdate(Q);
}

public void Off() throws SQLException{
this.conn.close();
}

}
Anuncios
A %d blogueros les gusta esto: