最近公司做个项目,要求把图片存放到数据库中然后再读取出来,在做的过程中老是出现这样或那样的问题,现把代码贴出来,仅供大家参考。
package com.swh.conImg;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ConImgDemo {
/**
* @param args
*/
Connection conn=null;
public ConImgDemo () {
try {
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=swhImg";
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
conn= DriverManager.getConnection(url,"sa","sa");
}
catch(SQLException e) {
e.printStackTrace();
}
catch(ClassNotFoundException ce) {
ce.printStackTrace();
}
}
public void Insert() {
try {
String sql="insert into picture values(?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
File f =new File("E:/Pictures/1.jpg");
FileInputStream input= new FileInputStream(f);
ps.setString(1,"test");
ps.setBinaryStream(2, input,(int)f.length());
ps.executeUpdate();
ps.close();
input.close();
}
catch(SQLException e) {
e.printStackTrace();
}
catch(IOException ie) {
ie.printStackTrace();
}
}
public void Read() {
try {
String sql="select picture from picture where name=?";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1, "test");
ResultSet rs=ps.executeQuery();
byte [] b=new byte[10240*8];
while(rs.next()) {
InputStream in=rs.getBinaryStream("picture");
in.read(b);
File f=new File("D:Pictures/3.jpg");
FileOutputStream out=new FileOutputStream(f);
out.write(b, 0, b.length);
out.close();
}
}
catch(SQLException e) {
e.printStackTrace();
}
catch(IOException ie) {
ie.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ConImgDemo conImgDemo=new ConImgDemo ();
conImgDemo.Insert();
conImgDemo.Read();
}
}
其实,主要是用文件输入,输出流来进行操作。
http://blog.csdn.net/sanfye/article/details/11788255