JAVA读取文件夹图片,并保存到Postgres数据库

import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.DriverManager;

public class mytest {

	public static void main(String[] args) {
		try {
			String strSQL = "";
			int k = 0, n = 0;
			Connection dbConn = null;
			PreparedStatement dbStat = null;
			String driver = "org.postgresql.Driver";
	        String url = "jdbc:postgresql://" + "127.0.0.1" + ":" + "5432" + "/" + "postgres";
	        Class.forName(driver);
	        dbConn= DriverManager.getConnection(url, "postgres", "pg");
	        
			// 上传图片,
			//图片存放路径:C:\Users\Administrator\Desktop\新生图片\1901班照片\张三.jpg
			//图片存放路径:C:\Users\Administrator\Desktop\新生图片\1902班照片\李四.jpg
			File file = new File(
					"C:\\Users\\Administrator\\Desktop\\新生图片\\");
			File[] firstfiles = file.listFiles();//一级目录列表
			for (int x = 0; x < firstfiles.length; x++) {
				File[] secondfiles = firstfiles[x].listFiles();//二级目录列表
				for (int i = 0; i < secondfiles.length; i++) {
				    //读取各二级目录的图片
					File file_picture = secondfiles[i];
					String filename = file_picture.getName().trim(); 
					strSQL = "INSERT INTO picture(name, zpian) VALUES (?, ?);";//zpian的字段类型bytea
					dbStat = dbConn.prepareStatement(strSQL);
					dbStat.setString(1, filename);
					// 设置图片文件
					FileInputStream inputStream = new FileInputStream(
							file_picture);
					//图片以二进制保存到数据库
					dbStat.setBinaryStream(2, inputStream,
							(int) file_picture.length());
					// 执行SQL
					dbStat.execute();
					k++;
				}
				System.out.println(firstfiles[x].getName() + ":" + k);
				n += k;
				k = 0;
			}
			dbStat.close();
			System.out.println("总量:" + n);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

你可能感兴趣的:(Java)