现在的位置: 首页 > 综合 > 正文

android 将图片保存到数据库

2014年01月21日 ⁄ 综合 ⁄ 共 1072字 ⁄ 字号 评论关闭
public class ExamJdbc11 { 
public static  void method1() { 
Connection conn = null;	
PreparedStatement stmt = null; 
try { 
conn = SQLHelper.getConnection(); 
String sql = "insert into tb_file values(?,?)"; 
stmt = conn.prepareStatement(sql); 
stmt.setString(1, "c:/1.jpg"); 

InputStream in = new FileInputStream("c:/1.jpg"); 
stmt.setBinaryStream(2, in, in.available());//存入图片的大小,这样才可以取得 
stmt.executeUpdate(); 
} catch (Exception e) { 
e.printStackTrace(); 
} finally { 
SQLHelper.close(null, stmt, conn); 
} 
} 
//取出来 
public static  void method2() { 
Connection conn = null; 
PreparedStatement stmt = null; 
ResultSet rs = null; 
try { 

conn = SQLHelper.getConnection(); 
String sql = "select * from tb_file where filename = ?"; 
stmt = conn.prepareStatement(sql); 
stmt.setString(1, "c:/1.jpg"); 
rs = stmt.executeQuery(); 
rs.next(); 

InputStream in = rs.getBinaryStream("filecontent"); 
FileOutputStream fout = new FileOutputStream("d:/2.jpg"); 
byte[] buff = new byte[1024]; 
int length = 0; 
while ((length = in.read(buff)) != -1) { 
fout.write(buff, 0, length); 
fout.flush(); 
} 
fout.close(); 
in.close(); 

} catch (Exception e) { 
e.printStackTrace(); 
} finally { 
SQLHelper.close(rs, stmt, conn); 
} 

} 

public static void main(String[] args){ 
method2(); 

} 
} 

抱歉!评论已关闭.