Thread View: es.comp.lenguajes.java
1 messages
1 total messages
Started by Guevonaso
Thu, 18 Jan 2007 10:50
Guardar Blob en Base de datos MySql 5
Author: Guevonaso
Date: Thu, 18 Jan 2007 10:50
Date: Thu, 18 Jan 2007 10:50
68 lines
3127 bytes
3127 bytes
Hola a todos.
Bueno, tengo un problema. Intento guardar un fichero binario en base de
datos MySql 5 pero me da un error de sintaxis al ejecutar la consulta
siguiente:
// content es un InputStream
String sql = "UPDATE datos " +
" SET imagen= ? " +
" WHERE id= ?";
PreparedStatement stm = conex.prepareStatement(sql);
stm.setBinaryStream(1, content, content.available());
stm.setInt(2, codResidente);
int cont = stm.executeUpdate(sql);
stm.close();
Me da un error de sintaxis (que no es tal). Deduzco que el problema es
del preparedStatement del driver.
El caso es que no funciona.
He encontrado una solucion, pero no me gusta por lo farragoso que
resulta. ¿Alguna otra idea?
La solucion que he encontrado ha sido mas o menos esta:
String sql = "SELECT imagen FROM datos WHERE id = ?";
String UPDATE_1 = " UPDATE datos SET imagen='X' WHERE id = " + cod;
String UPDATE_2 = " UPDATE datosSET imagen=? WHERE id = ?";
PreparedStatement stm = conex.prepareStatement(sql);
stm.setInt(1, codResidente);
ResultSet rs = stm.executeQuery();
Blob dato;
if (rs.next()) {
dato = rs.getBlob(1);
if (dato == null) {
rs.close();
stm.close();
Statement stm2 = conex.createStatement();
stm2.executeUpdate(UPDATE_1);
stm2.close();
stm = conex.prepareStatement(sql);
stm.setInt(1, codResidente);
rs = stm.executeQuery();
rs.next ();
dato = rs.getBlob(1);
stm.close();
}
int length;
byte[] buffer = new byte[1024];
int cont = 1;
while ((length = content.read(buffer,0, 1024)) != -1) {
log.debug("Iteracion " + cont);
dato.setBytes(cont,buffer, 0, length);
cont = cont + 1024;
}
stm = conex.prepareStatement(UPDATE_2);
stm.setBlob(1, dato);
stm.executeUpdate();
stm.close();
}
Funcionar funciona, pero obviamente no es la mejor solucion.
Thread Navigation
This is a paginated view of messages in the thread with full content displayed inline.
Messages are displayed in chronological order, with the original post highlighted in green.
Use pagination controls to navigate through all messages in large threads.
Back to All Threads