2012-11-28 37 views
0

我想在MySQl数据库中存储歌曲和歌词。我用Google搜索的例子如何做到这一点,但没有help.However,我能够存储图像:在MySQL数据库中存储歌曲(BLOB支持)

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 

谁能帮助我如何存储歌曲以实例,以及如何检索回来???

+1

我认为MySQL的是为存储照片和配方摆在首位,而不是歌曲。开玩笑。你是否遇到异常? – mbelow

+0

@mbelow以上代码?不! –

+0

执行查询后的状态是什么?是否创造了新纪录? Blob字段是否为空?请提供更多信息。 – mbelow

回答

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(); 
} 
+0

+1 answer.can请你解释: ps.setString(2 file.getName()); ps.setBinaryStream(3,fs,fs.available()); –

+1

'setString'用于设置文件的名称(可选,我认为这将是有用的时候检索文件)和'setBinaryStream'设置文件的内容。 – tibtof

+0

还有一件事情,让代码将文件保存在d盘中?如果是的话,我无法找到它:( –