Java 在MySQL数据库上存储歌曲(BLOb支持)
我试图在MySQl数据库上存储歌曲和歌词。我在谷歌上搜索了一些例子来了解如何做到这一点,但没有任何帮助。不过,我能够存储图像:Java 在MySQL数据库上存储歌曲(BLOb支持),java,mysql,database,blob,Java,Mysql,Database,Blob,我试图在MySQl数据库上存储歌曲和歌词。我在谷歌上搜索了一些例子来了解如何做到这一点,但没有任何帮助。不过,我能够存储图像: con = DriverManager.getConnection(connectionURL, "root", ""); PreparedStatement ps = con.prepareStatement("INSERT INTO image VALUES(?,?)"); File file = new File("E://guitar.gif"); Fil
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
有谁能帮我存储歌曲吗?举个例子?以及如何检索歌曲?存储歌曲与存储图像没有什么不同。您可以为文件名添加另一列,也可以执行类似的操作来存储文件:
//..
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();
}
不要忘记异常处理
编辑:另一个具有字节数组的版本:
写:
阅读:
我认为MySQL的设计初衷是存储照片和食谱,而不是存储歌曲。只是开玩笑。您是否收到异常?@mbelow上面的代码?没有!执行查询后的状态是什么?是否创建了新记录?blob字段是否为空?请提供更多信息。@mbelow执行查询后,BLOb字段包含如下二进制数据00001110000000。。。。(假设是)它确实创建了一个新记录。答案为+1。请解释一下:ps.setString(2,file.getName());ps.setBinaryStream(3,fs,fs.available())
setString
用于设置文件名(可选,我认为在检索文件时它会很有用)和setBinaryStream
用于设置文件内容。还有一件事。该代码是否将文件保存在d驱动器中?如果是,我找不到:(它没有插入声音文件。:(它没有插入声音文件。然后我将fs.available();更改为fs.read(),它工作了:),但仍然存在读取问题
//..
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();
}