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

本文介绍了一个Java程序,该程序能够将文件内容写入数据库,并从数据库中读取图片数据到本地文件。主要涉及使用Java进行文件操作及与SQL Server数据库的连接,通过PreparedStatement执行SQL语句实现数据的存取。

不知道好用不,先保存一下

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; } } }

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值