【问题标题】:Storing songs on MySQL Database (BLOb support)在 MySQL 数据库上存储歌曲(BLOb 支持)
【发布时间】:2012-11-16 12:40:24
【问题描述】:

我正在尝试在 MySQl db 上存储歌曲和歌词。我搜索了如何执行此操作的示例,但没有帮助。但是,我能够存储图像:

  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

谁能帮我如何存储歌曲?例如?以及如何找回它?

【问题讨论】:

  • 我认为 MySQL 最初的设计目的是存储照片和食谱,而不是歌曲。开玩笑。你有例外吗?
  • @mbelow 上面的代码?不!
  • 执行查询后是什么状态?是否创造了新记录? blob 字段是否为空?请提供更多信息。
  • @mbelow 执行查询后,BLOb 字段包含像这样的二进制数据 000011010000000....(假设是)它确实创建了一条新记录。

标签: java mysql database blob


【解决方案1】:

存储歌曲与存储图像没有什么不同。您可以为文件名添加另一列,并且您可以执行类似的操作来存储文件:

//..
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();
}

【讨论】:

  • +1 表示答案。你能解释一下吗:ps.setString(2, file.getName()); ps.setBinaryStream(3, fs,fs.available());
  • setString 用于设置文件名(可选,我认为在检索文件时会很有用),setBinaryStream 用于设置文件内容。
  • 还有一件事。该代码是否将文件保存在 d 驱动器中?如果是的话,我找不到它:(
  • 它没有插入声音文件。:(
  • 它没有插入声音文件。然后我改变了 fs.available();到 fs.read(),它工作:),但仍然有阅读问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
  • 1970-01-01
  • 2018-07-13
  • 2015-05-28
  • 2021-11-18
  • 2019-10-29
相关资源
最近更新 更多