package sundun.zfpt.gg.web;

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


public class InsertPic {
    
    /**
     * 插入图片到数据库(可以批量)
     */
    public static void InsrtPicToDB(){
        String sql = "insert into rdp0112.rdp_psignature(loginid,signature) values (?,?)";
        String filepath = "E:/images";
        File file = new File(filepath); 
        String [] filelist = file.list();
        
        Connection conn = null;
        PreparedStatement pst = null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            System.out.println("开始连接数据库");
            String url = "jdbc:oracle:thin:@10.196.20.11:1521:orcl"; 
            String user = "user";
            String password = "pass";
            conn = DriverManager.getConnection(url, user, password);
            pst = conn.prepareStatement(sql);
            
            int m = 0;
            for(int i=0;i<filelist.length;i++){
                File reaFile = new File(filepath + "\\" + filelist[i]);
                FileInputStream fis = new FileInputStream(reaFile);
                String photoName = "";
                if(filelist[i].length() >= 6){
                    photoName = filelist[i].substring(0, 6); //保存文件名当做一个字段的值
                    pst.setString(1, photoName);
                    pst.setBinaryStream(2, fis, (int) reaFile.length());
                    m++;
                    int n = pst.executeUpdate();
                    System.out.println(n + "条记录已经插入");
                }
            }
            System.out.println("本次一共导入" + m + "条");
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(pst != null){
                    pst.close();
                }
                if(conn != null){
                    conn.close();
                }
                System.out.println("数据库关闭");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        
    }

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

}