таблица mtable
полетипidintegerdatalongblobnamevarchar(255)
считывание контента
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
String qry = "select data from mtable where id = " + id;
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry);
if (rs.next()) {
InputStream in = rs.getBinaryStream("data");
BufferedInputStream bin = new BufferedInputStream(in);
int readed = - 1 ;
while ((readed = bin.read()) != - 1 ) {
out.write(readed); // out в данном случае - OutputStream некого сервлета
}
bin.close();
}
rs.close();
st.close();
вставка/апдейт, например, из файла
1.
2.
3.
4.
5.
6.
7.
File file = new File("c:\\content.doc");
FileBlobImpl fblob = new FileBlobImpl(file);
String qry = "update mtable set data = ? where id = " + id;
PreparedStatement pst = con.prepareStatement(query);
pst.setBlob( 1 , fblob);
pst.executeUpdate();
pst.close();
класс FileBlobImpl очень прост
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
import java.sql.*;
import java.io.*;
public class FileBlobImpl implements Blob {
private File file;
public FileBlobImpl(File file) {
this .file = file;
}
public long length() throws SQLException {
return file.length();
}
public byte [] getBytes( long pos, int length) throws SQLException {
if (pos + length >= length())
throw new SQLException("Bad lenght");
try {
RandomAccessFile raf = new RandomAccessFile(file, "r");
raf.seek(pos);
byte [] bytes = new byte [length];
for ( int i = 0 ; i < bytes.length; i++) {
bytes[i] = raf.readByte();
}
return bytes;
} catch (FileNotFoundException e) {
throw new SQLException("File is not found :" + e.toString());
} catch (IOException e) {
throw new SQLException("IO Exception while reading this file:" + e.toString());
}
}
public InputStream getBinaryStream() throws SQLException {
try {
return new FileInputStream(file);
} catch (FileNotFoundException e) {
throw new SQLException("File is not found :" + e.toString());
}
}
public long position( byte pattern[], long start) throws SQLException {
throw new UnsupportedOperationException();
}
public long position(Blob pattern, long start) throws SQLException {
throw new UnsupportedOperationException();
}
public int setBytes( long pos, byte [] bytes) throws SQLException {
throw new UnsupportedOperationException();
}
public int setBytes( long pos, byte [] bytes, int offset, int len) throws SQLException {
throw new UnsupportedOperationException();
}
public OutputStream setBinaryStream( long pos) throws SQLException {
throw new UnsupportedOperationException();
}
public void truncate( long len) throws SQLException {
throw new UnsupportedOperationException();
}
}