Jdbc操作Blob数据
package jdbc;
import org.junit.Test;
import java.io.*;
import java.sql.*;
public class PreparedStatementBlobTest {
@Test
public void test1() throws SQLException, FileNotFoundException {
Connection connection = JdbcUtils.getConnection();
String sql = "insert into customers(username,photo) values(?,?)";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setObject(1,"小明");
FileInputStream inputStream = new FileInputStream(new File("abc.jpg"));
ps.setBlob(2,inputStream);
ps.execute();
JdbcUtils.close(connection,ps);
}
@Test
public void test2() throws SQLException, IOException {
Connection connection = JdbcUtils.getConnection();
String sql = "select username,photo from customers where username = ? ";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setObject(1,"小明");
ResultSet rs = ps.executeQuery();
if (rs.next()) {
System.out.println(rs.getString(1));
Blob photo = rs.getBlob(2);
InputStream photoBinaryStream = photo.getBinaryStream();
FileOutputStream outputStream = new FileOutputStream(new File("abd.jpg"));
byte[] bytes = new byte[1024];
int len;
while ((len=photoBinaryStream.read(bytes))!=-1){
outputStream.write(bytes,0,len);
}
}
JdbcUtils.close(connection,ps,rs);
}
}