Lista completa de tipos de datos JDBC
Además de los tipos de datos que conoce, JDBC le permite trabajar con muchos tipos de datos nativos para DBMS. A continuación listaré los tipos y las funciones para conseguirlos:
Тип | Метод |
---|---|
Array | getArray() |
AsciiStream | getAsciiStream() |
BigDecimal | getBigDecimal() |
BinaryStream | getBinaryStream() |
Blob | getBlob() |
Boolean | getBoolean() |
Blob | getBlob() |
Boolean | getBoolean() |
Byte | getByte() |
Bytes | getBytes() |
CharacterStream | getCharacterStream() |
Clob | getClob() |
Date | getDate() |
Double | getDouble() |
Float | getFloat() |
Int | getInt() |
Long | getLong() |
NCharacterStream | getNCharacterStream() |
Object | getObject() |
Ref | getRef() |
RowId | getRowId() |
Short | getShort() |
SQLXML | getSQLXML() |
String | getString() |
Time | getTime() |
Timestamp | getTimestamp() |
UnicodeStream | getUnicodeStream() |
URL | getURL() |
Ya hemos considerado los tipos primitivos. Intentemos ahora trabajar con objetos.
tipo de datos BLOB
Si desea guardar algún objeto en la base de datos, la forma más sencilla de hacerlo es utilizando el tipo SQL BLOB. JDBC tiene su contraparte llamada Blob.
BLOB significa Objeto Binario Grande . _ _ Se utiliza para almacenar una matriz de bytes. El tipo Blob en JDBC es una interfaz y puede colocar (y recibir) datos en él de dos maneras:
- Uso de flujo de entrada
- Usando una matriz de bytes
Ejemplo: la columna número 3 contiene el tipo BLOB:
Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery("SELECT * FROM user");
results.first();
Blob blob = results.getBlob(3);
InputStream is = blob.getBinaryStream();
Para crear su propio objeto Blob, necesita usar la función createBlob() . Ejemplo:
String insertQuery = “INSERT INTO images(name, image) VALUES (?, ?)”;
PreparedStatement statement = connection.prepareStatement(insertQuery);
// Create a Blob object and get an OtputStream from it to write data to it
Blob blob = connection.createBlob();
// Populate the Blob with data...
OutputStream os = blob.setBinaryStream(1);
// Passing Blob as query parameter
statement.setBlob(2, blob);
statement.execute();
Hay dos formas de llenar un Blob con datos. El primero es a través de OutputSteam :
Path avatar = Paths.get("E:\\images\\cat.jpg");
OutputStream os = blob.setBinaryStream(1);
Files.copy(avatar, os);
Y el segundo, mediante el llenado de bytes:
Path avatar = Paths.get("E:\\images\\cat.jpg");
byte[] content = Files.readAllBytes(avatar);
blob.setBytes(1, content);
Guardar un objeto Java en una base de datos
Hemos aprendido a guardar objetos binarios en la base de datos: matrices de bytes, flujos de bytes, etc. ¿Qué pasa con los objetos de Java? ¿Cómo guardamos un objeto Java en una base de datos?
Digamos que tenemos una clase Java de empleado que describe a un empleado de una empresa:
public class Employee {
public Integer id;
public String name;
public String occupation;
public Integer salary;
public Date joinDate;
}
¿Cómo podemos guardar un objeto de esta clase en la base de datos usando JDBC?
De hecho, ya sabes todo lo que necesitas saber. Primero necesita crear una tabla en la base de datos que corresponda a esta clase. Por ejemplo, este:
CREATE TABLE employee {
id INT PRIMARY KEY NOT NULL,
name VARCHAR(100),
occupation VARCHAR(100),
salary INT,
join_date DATE
}
Y ahora escribamos el código que agregará un objeto de nuestra clase Empleado a la base:
public static boolean addEmployee(Connection connection, Employee employee) throws Exception {
// Create and prepare a query to insert data into the table
String insertQuery = "INSERT INTO employee(name, occupation, salary, join_date ) VALUES (?, ?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(insertQuery);
// Populate the query with data from the Employee object
statement.setString(1, employee.name);
statement.setString(2, employee.occupation);
statement.setInt(3, employee.salary);
statement.setDate(4, employee.joinDate);
// Execute our query and it returns true if a new row has been added
int count = statement.executeUpdate();
return count > 0;
}
Simple y claro. El método funcionará muy bien.
Lectura de un objeto Java de una base de datos
Aprendimos cómo escribir un objeto en la base de datos, ahora escribamos el código para leer el objeto de la base de datos. Comencemos con el código que lee un objeto de la base de datos por su ID:
public static Employee getEployeeById(Connection connection, int id) throws Exception {
// Create and prepare a query to get an employee from the table
PreparedStatement statement = connection.prepareStatement("SELECT * FROM employee WHERE id = ?");
statement.setInt(1, id);
// Execute our query and it returns null if there are no rows in the query result
ResultSet results = statement.executeQuery();
if (!results.first())
return null;
// Populate the Employee object with the data from the ResultSet
Employee employee = new Employee();
employee.id = results.getInt(1);
employee.name = results.getString(2);
employee.occupation = results.getString(3);
employee.salary = results.getInt(4);
employee.joinDate = results.getDate(5);
return employee;
}
¿Y si no necesitamos un objeto, sino varios? Tal solicitud también es fácil de escribir. Consigamos todos los empleados de nuestra empresa:
public static List<Employee> getAllEployees(Connection connection) throws Exception {
// Create and execute a query to get employees from the table
Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery("SELECT * FROM employee");
ArrayList<Employee> list = new ArrayList<Employee>();
while (results.next()) {
// Populate the Employee object with the data from the current row of the ResultSet
Employee employee = new Employee();
employee.id = results.getInt(1);
employee.name = results.getString(2);
employee.occupation = results.getString(3);
employee.salary = results.getInt(4);
employee.joinDate = results.getDate(5);
list.add(employee);
}
return list;
}
Por cierto, si hay muchos métodos de este tipo, en cada uno de ellos deberá escribir el mismo código para convertir la cadena ResultSet en un objetoempleado. Entonces, este código se puede mover a un método separado.
Esto puede ser especialmente útil si la clase Employee contiene campos complejos como Enum, InputStream o referencias a otros objetos que también queremos almacenar en la base de datos.
GO TO FULL VERSION