看代码:
package com.cmdi.test01;
import java.io.*;
import java.sql.*;
/**
* 将本地文件的图片传到数据库并下载
*/
public class Test1 {
private static String url="jdbc:postgresql://10.160.38.2:10110/functionaltest";
private static String user="gpadmin";
private static String password="gpadmin";
private static Connection con;
public static void main(String[] args) throws Exception {
Class.forName("org.postgresql.Driver");
con=DriverManager.getConnection(url,user,password);
shangchuan();
xiazai();
}
//添加图片到数据库
public static void shangchuan() throws Exception{
String sql="insert into test.image(name,content) values(?,?)";
PreparedStatement ptmt=con.prepareStatement(sql);
ptmt.setString(1, "美女.jpg");
InputStream is=null;
is=new FileInputStream("E:\\server\\1111.jpg");
ptmt.setBinaryStream(2, is,is.available());
ptmt.execute();
System.out.println("图片添加成功!");
}
//从数据库中把图片下载至桌面
public static void xiazai() throws Exception{
String sql="select content from test.image where name='美女.jpg' ";//在我这里3.jpg是第三张图片
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(sql);//将查询结果给rs
if(rs.next()){
InputStream is=rs.getBinaryStream("content");
FileOutputStream fos=new FileOutputStream("E:\\server\\upload\\美女.jpg");
byte[] buffer=new byte[1024];
int len=0;
while((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);//将数据库的图片写出
}
System.out.println("下载成功!请查看");
}else{
System.out.println("图片不存在!");
}
con.close();
}
}
打完收工》》》》