转----java读写SQLServer2005的image型字段

不知道好用不,先保存一下
package com.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class Test{
public Connection getCon(){
try{
//连接SQLServer2005
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=test","sa","sasa");
return con;
}catch(Exception ex){
ex.printStackTrace();
}
return null;
}

public static void main(String[] args){
try{
Test t = new Test();
t.writeFileToDb("D:/Aobh/mypic/S5001645.JPG");
t.readImgFromDb("D:/Aobh/mypic/S5001645.JPG","c:/new.jpg");
}catch(Exception ex){
ex.printStackTrace();
}
}


public void writeFileToDb(String fileName){
System.out.println("Writing to database... from file:"+fileName);
Connection con = null;
try{
con = getCon();
File myFile = new File(fileName);
InputStream in = new FileInputStream(myFile);
String sql = "insert into Table_1 (picname,pic) values(?,?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1,fileName);
ps.setBinaryStream(2,in,(int)myFile.length());
int result = ps.executeUpdate();
if (result>0)
System.out.println("Writing to database picfile success");
else
System.out.println("Writing to database picfile error");
}catch(Exception ex){
ex.printStackTrace();
}finally{
if (con !=null){
try{
con.close();
}catch(Exception ex){
ex.printStackTrace();
}
con = null;
}
}
}


public void readImgFromDb(String picName,String newName){
System.out.println("Reading from database to file:"+newName);
Connection con = null;
try{
con = getCon();
OutputStream out = new FileOutputStream(newName);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from Table_1 where picname='"+picName+"'");
if(rs.next()){
System.out.println(rs.getString("picname"));
int tmpi=0;
InputStream ins= rs.getBinaryStream("pic");
while((tmpi=ins.read())!=-1){
out.write(tmpi);
}
ins.close();
out.flush();
out.close();
System.out.println("Reading from database to file "+newName+" success");
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
if (con!=null){
try{
con.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
con = null;
}
}
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值