我正在尝试在MySQl db上存储歌曲和歌词。我用google搜索示例如何做到这一点,但没有帮助。但是,我能够存储图像:
con = DriverManager.getConnection(connectionURL, "root", "");
PreparedStatement ps = con.prepareStatement("INSERT INTO image VALUES(?,?)");
File file = new File("E://guitar.gif");
FileInputStream fs = new FileInputStream(file);
ps.setInt(1,id);
ps.setBinaryStream(2,fs,fs.available());
int i = ps.executeUpdate();
ps.close();
con.close();
//rest code
任何人都可以帮助我如何存储歌曲吗?例如?以及如何找回它?
答案 0 :(得分:2)
存储歌曲与存储图像没有什么不同。您可以为文件名添加另一列,您可以执行类似的操作来存储文件:
//..
PreparedStatement ps = con.prepareStatement("INSERT INTO data_table VALUES(?, ?, ?)");
//...
ps.setInt(1,id);
ps.setString(2, file.getName());
ps.setBinaryStream(3, fs,fs.available());
int i = ps.executeUpdate();
//...
然后检索它:
PreparedStatement ps = con.prepareStatement("SELECT file_name, content from data_table where *some condition*");
ResultSet rs = ps.executeQuery();
while(rs.hasNext) {
rs.next();
String fileName = rs.getString("file_name");
Blob blob = rs.getBlob("content");
byte[] content = blob.getBytes(1, (int) blob.length());
//now content contains the data, you ca store it in a file if you need
OutputStream os = new FileOutputStream(new File("d:/test/" + fileName));
os.write(content);
os.close();
}
不要忘记异常处理!
编辑:另一个带字节数组的版本: 写:
//..
PreparedStatement ps = con.prepareStatement("INSERT INTO data_table VALUES(?, ?, ?)");
//...
byte[] content = new byte[fs.available()];
ps.setInt(1,id);
ps.setString(2, file.getName());
ps.setBytes(3, content);
int i = ps.executeUpdate();
//...
读:
PreparedStatement ps = con.prepareStatement("SELECT file_name, content from data_table where *some condition*");
ResultSet rs = ps.executeQuery();
while(rs.hasNext) {
rs.next();
String fileName = rs.getString("file_name");
byte[] content = rs.getBytes("content");
//now content contains the data, you ca store it in a file if you need
OutputStream os = new FileOutputStream(new File("d:/test/" + fileName));
os.write(content);
os.close();
}