Java/Java 공부

DB에 파일 집어넣기

AristataIT 2016. 7. 25. 15:17

BLOB 파일을 DB에 집어 넣는 것은 사실 별로 권장하지 않는다고 합니다.

왜냐하면 DB의 용량이 커져서 select 등의 sql문을 실행할때 많은 리소스를 필요하기 때문입니다.

그렇다고 안배울수는 없죠?

 

일단 수업시간에 선생님께서 요구한 사항들은 다음과 같습니다.

1. MySQL 로 DB와 테이블을 생성할것.

2. Eclipse 로 DB와 연결하여 임의의 경로에 들어있는 파일을 DB에 넣을것.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class BLOBInputTest {
 
    //전역변수선언
    private Connection con;
    private String driverName = "com.mysql.jdbc.Driver";
    private String dbURL = "jdbc:mysql://localhost:포트번호/DB이름";
    
    public BLOBInputTest(String fileName) {
        try {
            Class.forName(driverName);
            con = DriverManager.getConnection(dbURL, "계정""비밀번호");
            
            int maxID = getMaxID(con) +1;
            File file = new File(fileName);
            int fileLength = (int)file.length();
            System.out.println("fileLength : "+fileLength);
            InputStream is = new FileInputStream(file);
            
            String sql ="insert into pds (id, filename, file) values (?,?,?)";
            PreparedStatement pstmt = con.prepareStatement(sql);
            pstmt.setInt(1, maxID);
            pstmt.setString(2, fileName);
            pstmt.setBinaryStream(3, is, fileLength);
            pstmt.executeUpdate();
            pstmt.close();
            con.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    protected int getMaxID(Connection con) throws SQLException{
        
        int maxID = 0;
        Statement stmt = con.createStatement();
        ResultSet result = stmt.executeQuery("select max(id) from pds");
        while(result.next()){
            maxID = result.getInt(1);
        }
        result.close();
        stmt.close();
        return maxID;
    }
    public static void main(String[] args) {
        String fileName = "C:\\Users\\aristata\\Pictures\\Saved Pictures\\icon_01.png";
        BLOBInputTest fileup = new BLOBInputTest(fileName);
        System.out.println("성공");
 
    }
 
}
 
cs