1

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

誰かが曲を保存する方法を教えてくれますか?例を使って?そしてそれを元に戻す方法はありますか?

4

1 に答える 1

2

曲を保存することは、画像を保存することと同じです。ファイル名用に別の列を追加することができ、ファイルを保存するために同様のことを行うことができます:

//..
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();
}
于 2012-11-28T15:51:51.837 に答える