java+mysql(blob类型)图片存取
java+mysql将图片存到数据库blob类型字段,并取出成文件。
直接上代码吧。
代码
package wfb.testImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class imageTest {
private String className = "com.mysql.jdbc.Driver";
private String url = "jdbc:mysql://ip地址:3306/数据库名";
private String user = "数据库用户名";
private String password = "对应密码";
private Connection conn = null;
@Before
public void before() throws Exception {
Class.forName(className);
conn = DriverManager.getConnection(url, user, password);
}
@After
public void after() throws Exception{
conn.close();
}
@Test
public void test() throws Exception {//将图片存到数据库
File file = new File("E:\\图片\\辉夜姬.jpg");
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = -1;
byte[] buf = new byte[1024];
while((len = fis.read(buf)) != -1) {//汇总字节流到内存
baos.write(buf, 0, len);
}
baos.close();
fis.close();
byte[] bytes = baos.toByteArray();//从内存取出字节流数组
Blob pic = conn.createBlob();
pic.setBytes(1, bytes);//把字节流设置给blob类
String sql = "insert into images(image) values (?)";
PreparedStatement ppst = conn.prepareStatement(sql);
ppst.setBlob(1, pic);
ppst.execute();
ppst.close();
}
@Test
public void test2() throws Exception {//从数据库取出图片成图片
String sql = "select image from images where id = 1";
ResultSet rs = conn.createStatement().executeQuery(sql);
if(rs.next()) {
Blob pic = rs.getBlob(1);
InputStream is = pic.getBinaryStream();
int len = -1;
byte[] buf = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((len = is.read(buf)) != -1) {
baos.write(buf, 0, len);
}
is.close();
baos.close();
byte[] bytes = baos.toByteArray();
File file = new File("E:\\waster\\辉夜姬.jpg");
FileOutputStream fos = new FileOutputStream(file);
fos.write(bytes);
fos.close();
}
}
}
如果有错误的地方,欢迎指正。虽然,应该也没人看2333