JDBC fue ideada para crear una interface común entre distintos proveedores de bases de datos. Supongamos que requiero conectarme a una BD Oracle y/o SQL Server, con JDBC podemos crear una conexión sin la necesidad de crear decenas o centenas de clases y sus respectivos métodos, pues JDBC contiene lo esencial para ello.
Existen cuatro tipos de drivers JDBC:
- DRIVER PUENTE JDBC-ODBC: Un ejemplo de su uso es cuando queremos conectarnos a una BD de Access o incluso Excel. Al parecer ya no está en uso.
- DRIVER NATIVO: El inconveniente es que la máquina cliente debe tener instalador el driver,a unque es más recomendable que el driver JDBC-ODBC.
- DRIVER INTERMEDIO (RED): no requiere ningún tipo de instalación den el equipo donde se ejecuta el programa.
- DRIVER PURO(JAVA): no requiere ningún tipo de configuración en la máquina cliente.
JDBC nos permite cargar el driver específico que necesitamos, crear la conexión a la BD, preparar y ejecutar sentencias SQL y visualizar los resultados de las consultas.
¿Cuáles son los pasos para usar JDBC?
Son cuatro pasos:
- Conectarnos a la BD: requerimos cargar el driver y crear la conexión.
- Ejecución de consultas: crear las sentencias SQL a ejecutar.
- Manipulación de registros: lectura, inserción, actualización y eliminación mediante lenguaje SQL(DML).
- Cerrar la conexión.
Cargar el driver
private static final String DRIVER_POSTGRES = "org.postgresql.Driver"; //... Class.forName(DRIVER_POSTGRES);
private static final String url = "jdbc:postgresql://localhost/BD"; private static final String user = "postgres"; private static final String password = "m1Cl4v3"; //Creamos la conexion Connection conn; //Postgres conn = DriverManager.getConnection(url, user, password); System.out.println("Conexion exitosa!!");
stm.execute(sql); rs = stm.executeQuery(sql); if(rs.next()) { //... rs.close(); }
conn.close(); //Comprobamos el cierre if(conn.isClosed() == true) { System.out.println("Conexion cerrada"); }
Ejemplo. Creamos una conexión a PostgreSQL.
- Clase Main.java
- Clase Contacto.java
- Clase ConexionPostgres.java
Contacto.java
package org.inforhomex.modelo; /** *@Author Fer Carraro * */ public class Contacto { private int id; private String nombre; private String telefono; public Contacto() { } public Contacto(int id, String nombre, String telefono) { super(); this.id = id; this.nombre = nombre; this.telefono = telefono; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } @Override public String toString() { return "Contacto [id=" + id + ", nombre=" + nombre + ", telefono=" + telefono + "]"; } }
ConexionPostgres.java
package org.inforhomex.conexion; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.swing.JOptionPane; import java.sql.SQLException; import java.sql.SQLSyntaxErrorException; import org.postgresql.util.PSQLException; import org.inforhomex.modelo.Contacto; public class ConexionPostgres { private static final String DRIVER_POSTGRES = "org.postgresql.Driver"; private static final String url = "jdbc:postgresql://localhost/curso"; private static final String user = "postgres"; private static final String password = "tuclave"; public static void conexion() throws SQLException, SQLSyntaxErrorException,ClassNotFoundException,PSQLException; { //Postgres Class.forName(DRIVER_POSTGRES); //Creamos la conexion Connection conn; //Postgres conn = DriverManager.getConnection(url, user, password); System.out.println("Conexion exitosa!!"); String sql; //Sentencia SQL Postgres sql = "select nombre, telefono from public.contactos limit 1"; Statement stm; ResultSet rs; Contacto contacto; stm = conn.createStatement(); if(stm != null) { //ejecutamos consulta System.out.println("Ejecutamos consulta..."); stm.execute(sql); rs = stm.executeQuery(sql); if(rs.next()) { System.out.println("Nombre: "+rs.getString("nombre")); System.out.println("Telefono: "+rs.getString("telefono")); contacto = new Contacto(); contacto.setId(1); contacto.setNombre(rs.getString("nombre")); contacto.setTelefono(rs.getString("telefono")); javax.swing.JOptionPane.showMessageDialog(null, contacto,"Contacto encontrado",JOptionPane.INFORMATION_MESSAGE); } //cerramos el ResultSet rs.close(); //cerramos consulta System.out.println("Cerramos consulta..."); stm.close(); } //Cerramos la conexion conn.close(); //Comprobamos el cierre if(conn.isClosed() == true) { System.out.println("Conexion cerrada"); } } }
Main.java
package org.inforhomex; import org.inforhomex.conexion.ConexionPostgres; import org.inforhomex.conexion.Conexion; import java.sql.SQLException; import java.sql.SQLSyntaxErrorException; import javax.swing.JOptionPane; import org.postgresql.util.PSQLException; /** *@Author Fer Carraro * */ public class Main { public static void main(String[] args) { System.out.println("Inicio"); try { //Nos conectamos a la BD ConexionPostgres.conexion(); } catch(PSQLException ex0) { JOptionPane.showMessageDialog(null, ex0.toString(),"PSQLException",JOptionPane.ERROR_MESSAGE); }catch (SQLSyntaxErrorException ex1) { JOptionPane.showMessageDialog(null, ex1.toString(),"SQLSyntaxErrorException",JOptionPane.ERROR_MESSAGE); } catch (SQLException ex2) { JOptionPane.showMessageDialog(null, ex2.toString(),"SQLException",JOptionPane.ERROR_MESSAGE); } catch (Exception ex3) { JOptionPane.showMessageDialog(null, ex3.toString(),"Exception",JOptionPane.ERROR_MESSAGE); }finally { System.out.println("Hecho"); } } }
Ejemplo completo en github:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.inforhomex.conexion; | |
/** | |
*@Author Fer Carraro | |
* | |
*/ | |
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.ResultSet; | |
import java.sql.Statement; | |
import javax.swing.JOptionPane; | |
import java.sql.SQLException; | |
import java.sql.SQLSyntaxErrorException; | |
import org.postgresql.util.PSQLException; | |
import org.inforhomex.modelo.Contacto; | |
public class Conexion { | |
private static final String DRIVER = "org.mariadb.jdbc.Driver"; | |
private static final String URL = "jdbc:mariadb://localhost:3306/miBD?user=root&password=root"; | |
public static void conexion() throws SQLException, SQLSyntaxErrorException,ClassNotFoundException,PSQLException { | |
//Registramos driver | |
Class.forName(DRIVER); | |
//Creamos la conexion | |
Connection conn = DriverManager.getConnection(URL); | |
System.out.println("Conexion exitosa!!"); | |
//Sentencia SQL | |
String sql = "select nombre, telefono from esquema.contactos limit 1"; | |
Statement stm; | |
ResultSet rs; | |
Contacto contacto; | |
stm = conn.createStatement(); | |
if(stm != null) { | |
//ejecutamos consulta | |
System.out.println("Ejecutamos consulta..."); | |
stm.execute(sql); | |
rs = stm.executeQuery(sql); | |
if(rs.next()) { | |
System.out.println("Nombre: "+rs.getString("nombre")); | |
System.out.println("Telefono: "+rs.getString("telefono")); | |
contacto = new Contacto(); | |
contacto.setId(1); | |
contacto.setNombre(rs.getString("nombre")); | |
contacto.setTelefono(rs.getString("telefono")); | |
javax.swing.JOptionPane.showMessageDialog(null, contacto,"Contacto encontrado",JOptionPane.INFORMATION_MESSAGE); | |
} | |
//cerramos el ResultSet | |
rs.close(); | |
//cerramos consulta | |
System.out.println("Cerramos consulta..."); | |
stm.close(); | |
} | |
//Cerramos la conexion | |
conn.close(); | |
//Comprobamos el cierre | |
if(conn.isClosed() == true) { | |
System.out.println("Conexion cerrada"); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.inforhomex.conexion; | |
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.ResultSet; | |
import java.sql.Statement; | |
import javax.swing.JOptionPane; | |
import java.sql.SQLException; | |
import java.sql.SQLSyntaxErrorException; | |
import org.postgresql.util.PSQLException; | |
import org.inforhomex.modelo.Contacto; | |
public class ConexionPostgres { | |
private static final String DRIVER_POSTGRES = "org.postgresql.Driver"; | |
private static final String url = "jdbc:postgresql://localhost/curso_udemy"; | |
private static final String user = "postgres"; | |
private static final String password = "5432"; | |
public static void conexion() throws SQLException, SQLSyntaxErrorException,ClassNotFoundException,PSQLException; { | |
//Postgres | |
Class.forName(DRIVER_POSTGRES); | |
//Creamos la conexion | |
Connection conn; | |
//Postgres | |
conn = DriverManager.getConnection(url, user, password); | |
System.out.println("Conexion exitosa!!"); | |
String sql; | |
//Sentencia SQL Postgres | |
sql = "select nombre, telefono from public.contactos limit 1"; | |
Statement stm; | |
ResultSet rs; | |
Contacto contacto; | |
stm = conn.createStatement(); | |
if(stm != null) { | |
//ejecutamos consulta | |
System.out.println("Ejecutamos consulta..."); | |
stm.execute(sql); | |
rs = stm.executeQuery(sql); | |
if(rs.next()) { | |
System.out.println("Nombre: "+rs.getString("nombre")); | |
System.out.println("Telefono: "+rs.getString("telefono")); | |
contacto = new Contacto(); | |
contacto.setId(1); | |
contacto.setNombre(rs.getString("nombre")); | |
contacto.setTelefono(rs.getString("telefono")); | |
javax.swing.JOptionPane.showMessageDialog(null, contacto,"Contacto encontrado",JOptionPane.INFORMATION_MESSAGE); | |
} | |
//cerramos el ResultSet | |
rs.close(); | |
//cerramos consulta | |
System.out.println("Cerramos consulta..."); | |
stm.close(); | |
} | |
//Cerramos la conexion | |
conn.close(); | |
//Comprobamos el cierre | |
if(conn.isClosed() == true) { | |
System.out.println("Conexion cerrada"); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.inforhomex.modelo; | |
/** | |
*@Author Fer Carraro | |
* | |
*/ | |
public class Contacto { | |
private int id; | |
private String nombre; | |
private String telefono; | |
public Contacto() { | |
} | |
public Contacto(int id, String nombre, String telefono) { | |
super(); | |
this.id = id; | |
this.nombre = nombre; | |
this.telefono = telefono; | |
} | |
public int getId() { | |
return id; | |
} | |
public void setId(int id) { | |
this.id = id; | |
} | |
public String getNombre() { | |
return nombre; | |
} | |
public void setNombre(String nombre) { | |
this.nombre = nombre; | |
} | |
public String getTelefono() { | |
return telefono; | |
} | |
public void setTelefono(String telefono) { | |
this.telefono = telefono; | |
} | |
@Override | |
public String toString() { | |
return "Contacto [id=" + id + ", nombre=" + nombre + ", telefono=" + telefono + "]"; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.inforhomex; | |
import org.inforhomex.conexion.ConexionPostgres; | |
import org.inforhomex.conexion.Conexion; | |
import java.sql.SQLException; | |
import java.sql.SQLSyntaxErrorException; | |
import javax.swing.JOptionPane; | |
import org.postgresql.util.PSQLException; | |
/** | |
*@Author Fer Carraro | |
* | |
*/ | |
public class Main { | |
public static void main(String[] args) { | |
System.out.println("Inicio"); | |
try { | |
Conexion.conexion(); | |
ConexionPostgres.conexion(); | |
} catch(PSQLException ex0) { | |
JOptionPane.showMessageDialog(null, ex0.toString(),"PSQLException",JOptionPane.ERROR_MESSAGE); | |
}catch (SQLSyntaxErrorException ex1) { | |
JOptionPane.showMessageDialog(null, ex1.toString(),"SQLSyntaxErrorException",JOptionPane.ERROR_MESSAGE); | |
} catch (SQLException ex2) { | |
JOptionPane.showMessageDialog(null, ex2.toString(),"SQLException",JOptionPane.ERROR_MESSAGE); | |
} catch (Exception ex3) { | |
JOptionPane.showMessageDialog(null, ex3.toString(),"Exception",JOptionPane.ERROR_MESSAGE); | |
}finally { | |
System.out.println("Hecho"); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<project xmlns="http://maven.apache.org/POM/4.0.0" | |
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | |
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | |
<modelVersion>4.0.0</modelVersion> | |
<groupId>org.inforhomex</groupId> | |
<artifactId>conectabd</artifactId> | |
<version>0.0.1-SNAPSHOT</version> | |
<packaging>app-client</packaging> | |
<name>conectabd</name> | |
<properties> | |
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir> | |
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | |
</properties> | |
<dependencies> | |
<dependency> | |
<groupId>javax</groupId> | |
<artifactId>javaee-api</artifactId> | |
<version>7.0</version> | |
<scope>provided</scope> | |
</dependency> | |
<dependency> | |
<groupId>org.mariadb.jdbc</groupId> | |
<artifactId>mariadb-java-client</artifactId> | |
<version>2.5.2</version> | |
</dependency> | |
<dependency> | |
<groupId>postgresql</groupId> | |
<artifactId>postgresql</artifactId> | |
<version>9.1-901.jdbc4</version> | |
</dependency> | |
</dependencies> | |
<build> | |
<plugins> | |
<plugin> | |
<groupId>org.apache.maven.plugins</groupId> | |
<artifactId>maven-compiler-plugin</artifactId> | |
<version>3.1</version> | |
<configuration> | |
<source>1.7</source> | |
<target>1.7</target> | |
<compilerArguments> | |
<endorseddirs>${endorsed.dir}</endorseddirs> | |
</compilerArguments> | |
</configuration> | |
</plugin> | |
<plugin> | |
<groupId>org.apache.maven.plugins</groupId> | |
<artifactId>maven-acr-plugin</artifactId> | |
<version>1.0</version> | |
<extensions>true</extensions> | |
<configuration> | |
<archive> | |
<manifest> | |
<mainClass>org.inforhomex.Main</mainClass> | |
</manifest> | |
</archive> | |
</configuration> | |
</plugin> | |
<plugin> | |
<groupId>org.apache.maven.plugins</groupId> | |
<artifactId>maven-dependency-plugin</artifactId> | |
<version>2.6</version> | |
<executions> | |
<execution> | |
<phase>validate</phase> | |
<goals> | |
<goal>copy</goal> | |
</goals> | |
<configuration> | |
<outputDirectory>${endorsed.dir}</outputDirectory> | |
<silent>true</silent> | |
<artifactItems> | |
<artifactItem> | |
<groupId>javax</groupId> | |
<artifactId>javaee-endorsed-api</artifactId> | |
<version>7.0</version> | |
<type>jar</type> | |
</artifactItem> | |
</artifactItems> | |
</configuration> | |
</execution> | |
</executions> | |
</plugin> | |
</plugins> | |
</build> | |
</project> |
https://www.javatpoint.com/jdbc-driver
http://codigoxules.org/conectar-mysql-utilizando-driver-jdbc-java-mysql-jdbc/