在MySQL数据库上存储歌曲(BLOb支持) [英] Storing songs on MySQL Database (BLOb support)

查看:192
本文介绍了在MySQL数据库上存储歌曲(BLOb支持)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在MySQl db上存储歌曲和歌词。我尝试了如何做到这一点,但没有帮助。但是,我能够存储图像:

I am trying to store songs and lyrics on MySQl db. I googled for examples how to do this,but no help.However,i am able to store images:

  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

任何人都可以帮助我如何存储歌曲?如何检索它?

Can anyone help me how to store songs?with example?and how to retrieve it back?

推荐答案

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

There's nothing different in storing a song than storing an image. You could add another column for the file name's, and the you can do something similar to store the files:

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

不要忘记异常处理!

EDIT:带有字节数组的另一个版本:
Write:

Another version with byte arrays: Write:

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

这篇关于在MySQL数据库上存储歌曲(BLOb支持)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆