有什么方法可以将文件附加到Java中的mysql吗?我需要将文件放置在数据库中而不是路径中。
答案 0 :(得分:0)
这是示例代码如何将二进制文件(如PDF文档,MS Excel电子表格,JPG / PNG图像文件或ZIP文件等)写入BLOB类型的数据库表列并进行读取的示例代码从数据库中获取。
在Java SE 7或更高版本中,我分别在Apache Derby(又名Java DB)和MySQL数据库中使用了这些功能。
德比: 写入数据库:
Path path = Paths.get("MyPic.jpg");
InputStream instream = Files.newInputStream(path);
PreparedStatement pstmnt = getConnection().prepareStatement(dml); // dml is an sql Insert
pstmnt.setBinaryStream(1, instream);
// pstmnt.setNull(1, Types.BLOB); // to set null value in db
pstmnt.executeUpdate();
pstmnt.close();
instream.close();
从数据库读取:
PreparedStatement pstmnt = getConnection().prepareStatement(sql); // sql is a Select
ResultSet rs = pstmnt.executeQuery();
rs.next();
InputStream instream = rs.getBinaryStream("col_name");
Path path = Paths.get("MyPic.jpg");
OutputStream outstream = Files.newOutputStream(path);
int len = 0;
byte [] buf = new byte [1024];
while ((len = instream.read(buf)) > 0) {
outstream.write(buf, 0, len);
}
instream.close();
outstream.flush();
outstream.close();
pstmnt.close();
MySQL:
写入数据库:
PreparedStatement pstmnt_= conn.prepareStatement(DML) // sql Insert
InputStream instream = Files.newInputStream(filePath); // filePath is of type Path
pstmnt.setBinaryStream(1, instream);
pstmnt.executeUpdate();
// close resources here
从数据库读取:
PreparedStatement pstmnt = conn.prepareStatement(DML); // sql Select
ResultSet rs = pstmnt.executeQuery();
rs.next();
Blob blob = rs.getBlob("col_name");
long len = blob.length();
byte [] fileBytes = blob.getBytes(1L, (int) len); // start pos = 1L
OutputStream out = ...
out.write(fileBytes);
out.flush();
out.close();
请注意,在使用JDBC对象(例如PreparedStatement
)和文件io流(例如InputStream
)之后,请确保这些资源已关闭。
答案 1 :(得分:-1)
使用base64 enconding并将其另存为BLOB数据
这是编码示例:
/**
* Method used for encode the file to base64 binary format
* @param file
* @return encoded file format
*/
private String encodeFileToBase64Binary(File file){
String encodedfile = null;
try {
FileInputStream fileInputStreamReader = new FileInputStream(file);
byte[] bytes = new byte[(int)file.length()];
fileInputStreamReader.read(bytes);
encodedfile = Base64.encodeBase64(bytes).toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encodedfile;
}