java将MP3文件存入数据库并取出

package jdbc.demo;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.sql.rowset.serial.SerialBlob;

import jdbc.utils.JdbcUtils;

import org.apache.commons.io.IOUtils;
import org.junit.Test;

/*
 * 对mp3进行处理
 */
public class BigDataDmeo {
	@Test
	public void saveMp3() throws Exception{
		Connection con = JdbcUtils.getConnection();
		//给出模板
		String sql = "insert into tab_bin values(?,?,?)";
		//创建pstmt
		PreparedStatement pstmt = con.prepareStatement(sql);
//		设置参数
		pstmt.setInt(1, 1);
		pstmt.setString(2, "独角戏.mp3");
		//把文件变成byte再创建Blob
		byte[] bytes = IOUtils.toByteArray(new FileInputStream("d:\\独角戏.mp3"));
		Blob blob = new SerialBlob(bytes);
		pstmt.setBlob(3, blob);
		
		pstmt.executeUpdate();
	}
	
	/*
	 * 拿到MP3
	 */
	@Test
	public void takeMp3() throws Exception{
		Connection con = JdbcUtils.getConnection();
		
		String sql = "select * from tab_bin";
		
		PreparedStatement pstmt = con.prepareStatement(sql);
		
		ResultSet rs = pstmt.executeQuery();
		
		if(rs.next()){
			Blob blob = rs.getBlob("data");
			
			InputStream in = blob.getBinaryStream();
			OutputStream out = new FileOutputStream("e:/djx.mp3");
			IOUtils.copy(in, out);
		}

	}
}

将加载数据库的代码分离了

package jdbc.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtils {
	public static Properties props = null; 
	static{
		//加载配置文件
		InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("dbconfig.properties");
		props = new Properties();
		try {
			props.load(in);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		
		//加载驱动类
		try {
			Class.forName(props.getProperty("driverClassName"));
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static Connection getConnection() throws SQLException{
		
		return DriverManager.getConnection(props.getProperty("url"),props.getProperty("username"), props.getProperty("password"));
	}
}


你可能感兴趣的:(数据库)