You need to sign in or sign up before continuing.
Commit a5f70e4c authored by Administrator's avatar Administrator

Initial commit

parents
#Eclipse
.settings
.project
.classpath
#Maven
target
#General
bak
This diff is collapsed.
# Ejemplos de JDBC
Ejemplos de JDBC incluidos en el Tema 4 de la asignatura DAI.
\ No newline at end of file
CREATE DATABASE IF NOT EXISTS dai;
CREATE USER IF NOT EXISTS 'dai'@'localhost' IDENTIFIED BY 'dai';
CREATE USER IF NOT EXISTS 'dai2'@'localhost' IDENTIFIED BY 'dai';
GRANT ALL ON dai.* TO 'dai'@'localhost' WITH GRANT OPTION;
GRANT ALL ON dai.user TO 'dai'@'localhost';
\ No newline at end of file
<?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>es.uvigo.esei.dai</groupId>
<artifactId>jdbc</artifactId>
<version>1.0.0</version>
<name>Ejemplos de DAI - JDBC</name>
<inceptionYear>2014</inceptionYear>
<url>https://sing-group.org/dt/gitlab/dai-2324/jdbc</url>
<developers>
<developer>
<name>Miguel Reboiro-Jato</name>
<organization>Escola Superior de Enxeñaría Informática -
Universidade de Vigo</organization>
<organizationUrl>https://esei.uvigo.es/</organizationUrl>
<email>mrjato@uvigo.gal</email>
</developer>
</developers>
<licenses>
<license>
<name>GNU GENERAL PUBLIC LICENSE, Version 3</name>
<url>http://www.gnu.org/licenses/gpl.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Dependencies versions -->
<mysql-connector-j.version>8.1.0</mysql-connector-j.version>
<!-- Plugin versions -->
<license-maven-plugin.version>2.2.0</license-maven-plugin.version>
<maven-compiler-plugin.version>3.11.0</maven-compiler-plugin.version>
<!-- license-maven-plugin configuration -->
<license.licenseName>gpl_v3</license.licenseName>
<license.copyrightOwners>Miguel Reboiro Jato</license.copyrightOwners>
<license.organizationName>Universidade de Vigo</license.organizationName>
<license.addJavaLicenseAfterPackage>false</license.addJavaLicenseAfterPackage>
</properties>
<contributors>
<contributor>
<name>Miguel Reboiro Jato</name>
<email>mrjato@uvigo.gal</email>
<organization>Escola Superior de Enxeñaría Informática -
Universidade de Vigo</organization>
<organizationUrl>https://esei.uvigo.es/</organizationUrl>
<roles>
<role>author</role>
<role>professor</role>
</roles>
</contributor>
</contributors>
<dependencies>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>${mysql-connector-j.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>license-maven-plugin</artifactId>
<version>${license-maven-plugin.version}</version>
<executions>
<execution>
<id>first</id>
<goals>
<goal>update-file-header</goal>
</goals>
<phase>process-sources</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
/*-
* #%L
* Ejemplos de DAI - JDBC
* %%
* Copyright (C) 2014 - 2023 Miguel Reboiro Jato
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package es.uvigo.esei.dai.jdbc.examples;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnectionExamples {
private static final String DB_URL = "jdbc:mysql://localhost/dai";
private static final String DB_USER = "dai";
private static final String DB_PASSWORD = "dai";
public static void main(String[] args) throws Exception {
statementCreate();
statementGrant();
statementInsert();
preparedStatementInsert();
statementSelect();
preparedStatementSelect();
transaction();
}
private static void statementCreate() throws SQLException {
// 1. Conexión a la base de datos
try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
// 2. Creación de la consulta
try (Statement statement = connection.createStatement()) {
// 3. Creación de la tabla Ejemplo
int result = statement.executeUpdate(
"CREATE TABLE Ejemplo("
+ "id INT NOT NULL AUTO_INCREMENT,"
+ "nombre VARCHAR(255) NOT NULL,"
+ "PRIMARY KEY (id)"
+ ")"
);
// 4. Comprobación de resultado
if (result != 0)
throw new SQLException("Unexpected result value: " + result);
}
}
}
private static void statementGrant() throws SQLException {
// 1. Conexión a la base de datos
try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
// 2. Creación de la consulta
try (Statement statement = connection.createStatement()) {
// 3. Modificación de permisos para dai2
int result = statement.executeUpdate("GRANT SELECT ON dai.Ejemplo TO 'dai2'@'localhost' ");
// 4. Comprobación de resultado
if (result != 0)
throw new SQLException("Unexpected result value: " + result);
}
}
}
private static void statementInsert() throws SQLException {
// 1. Conexión a la base de datos
try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
// 2. Creación de la consulta
try (Statement statement = connection.createStatement()) {
// 3. Creación de la tabla Ejemplo. Con RETURN_GENERATED_KEYS
// hacemos que las claves primarias se puedan recuperar
int result = statement.executeUpdate(
"INSERT INTO Ejemplo (id, nombre) VALUES (0, 'Ana'), (0, 'Juan')", Statement.RETURN_GENERATED_KEYS
);
// 4. Comprobación de resultado
if (result == 2) {
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
while (generatedKeys.next()) {
System.out.println("Clave " + generatedKeys.getInt(1));
}
}
} else {
throw new SQLException("Unexpected result value: " + result);
}
}
}
}
private static void preparedStatementInsert() throws SQLException {
// 1. Conexión a la base de datos
try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
// 2. Creación de la consulta. Con RETURN_GENERATED_KEYS
// hacemos que las claves primarias se puedan recuperar
try (
PreparedStatement statement = connection.prepareStatement(
"INSERT INTO Ejemplo (id, nombre) VALUES (0, ?), (0, ?)", Statement.RETURN_GENERATED_KEYS
)
) {
// 3. Asignación de los valores
statement.setString(1, "Ana");
statement.setString(2, "Juan");
// 4. Creación de la tabla Ejemplo.
int result = statement.executeUpdate();
// 5. Comprobación de resultado
if (result == 2) {
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
while (generatedKeys.next()) {
System.out.println("Clave " + generatedKeys.getInt(1));
}
}
} else {
throw new SQLException("Unexpected result value: " + result);
}
}
}
}
private static void statementSelect() throws SQLException {
// 1. Conexión a la base de datos local "dai"
// con login y password "dai"
try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
// 2. Creación de la consulta
try (Statement statement = connection.createStatement()) {
// 3. Ejecución de la consulta
try (ResultSet result = statement.executeQuery("SELECT * FROM Ejemplo WHERE nombre LIKE 'A%'")) {
// 4. Visualización de los resultados
while (result.next()) {
System.out.printf("Id: %d, Nombre: %s%n", result.getInt(1), result.getString(2));
}
}
}
}
}
private static void preparedStatementSelect() throws SQLException {
// 1. Conexión a la base de datos
try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
// 2. Preparación de la consulta
try (
PreparedStatement statement = connection
.prepareStatement("SELECT * FROM Ejemplo WHERE id > ? AND nombre LIKE ?")
) {
// 3. Asignación de los valores
statement.setInt(1, 5);
statement.setString(2, "A%");
// 4. Ejecución de la consulta
try (ResultSet result = statement.executeQuery()) {
// 5. Visualización de resultado
while (result.next()) {
System.out.printf("Id: %d, Nombre: %s%n", result.getInt("id"), result.getString("nombre"));
}
}
}
}
}
private static void transaction() throws Exception {
// 1. Conexión a la base de datos
try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
// 2. Activación del modo transacción
connection.setAutoCommit(false);
connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
// 3. Creación de la consulta
try (
PreparedStatement statement = connection.prepareStatement("INSERT INTO Ejemplo (id, nombre) VALUES (0, ?)")
) {
// 4. Asignación de los valores y ejecución de la consulta
for (String nombre : new String[] { "María", "Juan", "Luisa" }) {
statement.setString(1, nombre);
if (statement.executeUpdate() != 1) {
throw new SQLException("Error inserting value");
}
// 5. Fuerza que se haga un rollback cuando se intente insertar
// segundo nombre, de modo que se cancelará también la primera
// inserción
if (nombre.equals("Juan"))
throw new RuntimeException();
}
// 5a. Commit
connection.commit();
} catch (Exception e) {
// 5b. Rollback
connection.rollback();
}
}
}
}
/*-
* #%L
* Ejemplos de DAI - JDBC
* %%
* Copyright (C) 2014 - 2023 Miguel Reboiro Jato
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
package es.uvigo.esei.dai.jdbc.transactions;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TransactionExamples {
private static final String DB_URL = "jdbc:mysql://localhost/dai";
private static final String DB_USER = "dai";
private static final String DB_PASSWORD = "dai";
private static final int ISOLATION_LEVEL = Connection.TRANSACTION_READ_UNCOMMITTED;
public static void main(String[] args) throws Exception {
lostUpdate();
dirtyRead();
nonRepeatableRead();
phantomRead();
}
private static Connection createConnection() throws SQLException {
return DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
}
// Java no es capaz de manejar este tipo de problemas.
// La ejecución de este método puede bloquear la ejecución.
private static void lostUpdate() throws SQLException {
try (Connection connectionA = createConnection(); Connection connectionB = createConnection()) {
connectionA.setTransactionIsolation(ISOLATION_LEVEL);
connectionB.setTransactionIsolation(ISOLATION_LEVEL);
connectionA.setAutoCommit(false);
connectionB.setAutoCommit(false);
String update = "UPDATE Ejemplo SET nombre=? WHERE id = 1";
try (
PreparedStatement psA = connectionA.prepareStatement(update);
PreparedStatement psB = connectionB.prepareStatement(update)
) {
psA.setString(1, "NombreA");
psB.setString(1, "NombreB");
psA.executeUpdate();
psB.executeUpdate();
connectionA.commit();
connectionB.rollback();
System.out.println("Lost Update completed");
} catch (Exception e) {
System.out.println("Lost Update error");
e.printStackTrace();
}
}
}
private static void dirtyRead() throws SQLException {
try (Connection connectionA = createConnection(); Connection connectionB = createConnection()) {
connectionA.setTransactionIsolation(ISOLATION_LEVEL);
connectionB.setTransactionIsolation(ISOLATION_LEVEL);
connectionA.setAutoCommit(false);
connectionB.setAutoCommit(false);
String update = "UPDATE Ejemplo SET nombre=? WHERE id = 1";
String select = "SELECT * FROM Ejemplo WHERE id = 1";
try (
PreparedStatement psA = connectionA.prepareStatement(select);
PreparedStatement psB = connectionB.prepareStatement(update)
) {
psB.setString(1, "NombreB");
psB.executeUpdate();
try (ResultSet rs = psA.executeQuery()) {
rs.next();
System.out.println(rs.getString("nombre"));
}
connectionB.rollback();
connectionA.commit();
System.out.println("Dirty Read completed");
} catch (Exception e) {
System.out.println("Dirty Read error");
e.printStackTrace();
}
}
}
private static void nonRepeatableRead() throws SQLException {
try (Connection connectionA = createConnection(); Connection connectionB = createConnection()) {
connectionA.setTransactionIsolation(ISOLATION_LEVEL);
connectionB.setTransactionIsolation(ISOLATION_LEVEL);
connectionA.setAutoCommit(false);
connectionB.setAutoCommit(false);
String select = "SELECT * FROM Ejemplo WHERE id = 1";
String update = "UPDATE Ejemplo SET nombre=? WHERE id = 1";
try (
PreparedStatement psA = connectionA.prepareStatement(select);
PreparedStatement psB = connectionB.prepareStatement(update);
) {
try (ResultSet rs = psA.executeQuery()) {
rs.next();
System.out.println("Read 1: " + rs.getString("nombre"));
}
psB.setString(1, "NombreB");
psB.executeUpdate();
connectionB.commit();
try (ResultSet rs = psA.executeQuery()) {
rs.next();
System.out.println("Read 2: " + rs.getString("nombre"));
}
connectionA.commit();
System.out.println("Non-repeabable Read completed");
// No forma parte de la "Lectura no repetible"
// Vuelve a dejar la base de datos como estaba para continuar con los ejemplos
psB.setString(1, "Ana");
psB.executeUpdate();
connectionB.commit();
} catch (Exception e) {
System.out.println("Non-repeabable Read error");
e.printStackTrace();
}
}
}
private static void phantomRead() throws SQLException {
try (Connection connectionA = createConnection(); Connection connectionB = createConnection()) {
connectionA.setTransactionIsolation(ISOLATION_LEVEL);
connectionB.setTransactionIsolation(ISOLATION_LEVEL);
connectionA.setAutoCommit(false);
connectionB.setAutoCommit(false);
String select = "SELECT COUNT(*) FROM Ejemplo WHERE nombre=?";
String update = "INSERT INTO Ejemplo (nombre) VALUES (?)";
try (
PreparedStatement psA = connectionA.prepareStatement(select);
PreparedStatement psB = connectionB.prepareStatement(update);
) {
psA.setString(1, "Ana");
try (ResultSet rs = psA.executeQuery()) {
rs.next();
System.out.println("Read 1: " + rs.getInt(1));
}
psB.setString(1, "Ana");
psB.executeUpdate();
connectionB.commit();
try (ResultSet rs = psA.executeQuery()) {
rs.next();
System.out.println("Read 2: " + rs.getInt(1));
}
connectionA.commit();
System.out.println("Phantom Read completed");
} catch (Exception e) {
System.out.println("Phantom Read error");
e.printStackTrace();
}
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment