2012-11-28 40 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盤中?如果是的話,我無法找到它:( –