1. 首先在数据库中建立相应的表,用来存储要保存的二进制数据;比如
建立filedoc表,表结构如下:
ID varchar(50) not null;
fileType varchar(50) null;
fileName varchar(50) null;
filedoc image(16) null;
fileSize varchar(254) null;2.数据库的连接及语句集自己获得了:),然后调用如下方法
public boolean fileTodbS(Connection con,Statement sm,byte[] tBytes,String id,String filetype,String filename,int filesize) {
byte[] tByte;
String strSQL;
PreparedStatement ps;
tByte = tBytes; strSQL = "insert into filedoc(id,filetype,filename,filesize) values('"+id+"','"+filetype+"','"+filename+"','"+String.valueOf(filesize)+"')";
try {
if(sm.executeUpdate(sqlstr)>0){
strSQL = "update filedoc set filedoc=? where id='"+id+"'";
ps = con.prepareStatement(strSQL);
ByteArrayInputStream bais = new ByteArrayInputStream(tByte);
ps.setBinaryStream(1,bais,tByte.length);
if (ps.executeUpdate()>0) {
tByte = null;
return true;
}else {
tByte = null;
return false;
}
}else {
System.out.println("保存文件基本信息至数据库表filedoc时发生错误");
tByte = null;
return false;
}
catch(Exception ex) {
System.out.println("保存附件至数据库表filedoc时发生错误!"+ex.getMessage());
tByte = null;
return false;
}
}
建立filedoc表,表结构如下:
ID varchar(50) not null;
fileType varchar(50) null;
fileName varchar(50) null;
filedoc image(16) null;
fileSize varchar(254) null;2.数据库的连接及语句集自己获得了:),然后调用如下方法
public boolean fileTodbS(Connection con,Statement sm,byte[] tBytes,String id,String filetype,String filename,int filesize) {
byte[] tByte;
String strSQL;
PreparedStatement ps;
tByte = tBytes; strSQL = "insert into filedoc(id,filetype,filename,filesize) values('"+id+"','"+filetype+"','"+filename+"','"+String.valueOf(filesize)+"')";
try {
if(sm.executeUpdate(sqlstr)>0){
strSQL = "update filedoc set filedoc=? where id='"+id+"'";
ps = con.prepareStatement(strSQL);
ByteArrayInputStream bais = new ByteArrayInputStream(tByte);
ps.setBinaryStream(1,bais,tByte.length);
if (ps.executeUpdate()>0) {
tByte = null;
return true;
}else {
tByte = null;
return false;
}
}else {
System.out.println("保存文件基本信息至数据库表filedoc时发生错误");
tByte = null;
return false;
}
catch(Exception ex) {
System.out.println("保存附件至数据库表filedoc时发生错误!"+ex.getMessage());
tByte = null;
return false;
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货