Blob类型数据的读写
IO流知识
setBlob
getBinaryStream
import com.miyon.jdbc.JDBCUtils;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.*;
/**
* 演示Blob类型数据的存取
*
*
*/
public class TestBlob {
//存图片
@Test
public void testSave() throws Exception {
//1.创建连接
Connection connection = JDBCUtils.getConnection();
//2.执行修改
PreparedStatement statement = connection.prepareStatement("UPDATE BEAUTY SET photo=? WHERE id=1");
statement.setBlob(1,new FileInputStream("src\\liuyan.png"));
int update = statement.executeUpdate();
//3.关闭连接
JDBCUtils.close(null,statement,connection);
}
//读图片
@Test
public void testRead() throws Exception {
//1.创建连接
Connection connection = JDBCUtils.getConnection();
//2.执行修改
PreparedStatement statement = connection.prepareStatement("SELECT photo FROM beauty WHERE id=1");
ResultSet set = statement.executeQuery();
if(set.next()){
//方式1
// Blob blob = set.getBlob("photo");
// InputStream binaryStream = blob.getBinaryStream();
//方式2
InputStream inputStream = set.getBinaryStream("photo");
// FileOutputStream fos = new FileOutputStream("f:\\demo");
FileOutputStream fos = new FileOutputStream("src\\beauty.jpg");
//IO流知识。
int len;
byte [] b = new byte[1024];
while((len=inputStream.read(b))!=-1){
fos.write(b,0,len);
}
fos.close();
inputStream.close();
}
//3.关闭连接
JDBCUtils.close(null,statement,connection);
}
}