其实也没有什么,就拿mysql为例;
现在数据库建表,
让后写一个测试类
经本人测试绝对可用
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
/**
*在mysql数据库里成功测试,并且发现mysql的blob数据库不支持存储图片,只支持
*65535字节以下的本本数据存储。不过其他的大型数据库是支持储存图片的.
*/
public class InsertBlob {
public static void main(String[] args) {
try{
File f = new File("C:\\bsmain_runtime.log");
long length = f.length();
FileInputStream fis = new FileInputStream("C:\\bsmain_runtime.log");
byte[] imageBytes=new byte[(int)length];
int byteLength=fis.read(imageBytes, 0, (int)length);
ByteArrayInputStream bais=new ByteArrayInputStream(imageBytes);
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/test","root","java");
PreparedStatement pstmt = null;
/*
create table mypicture
( name varchar(20),
image blob );
*/
pstmt = con.prepareStatement("insert into mypicture(name,image) values(?,?)");
pstmt.setString(1, "001");
pstmt.setBinaryStream(2,bais,byteLength);
pstmt.executeUpdate();
System.out.println("file length:"+length);
System.out.println("byte length:"+byteLength);
System.out.println("插入成功.");
}catch(Exception e){
e.printStackTrace();
}
}
}