'PostgreSQL'에 해당되는 글 3건

  1. 2016.03.29 PostgreSQL Processing Binary Data in JDBC
  2. 2016.03.11 postgresql merge into
  3. 2016.01.05 PostgreSQL 9.4.0 문서
PostgreSQL2016. 3. 29. 14:50
반응형

For example, suppose you have a table containing the file names of images and you also want to store the image in a bytea column:

CREATE TABLE images (imgname text, img bytea);

To insert an image, you would use:

File file = new File("myimage.gif");
FileInputStream fis = new FileInputStream(file);
PreparedStatement ps = conn.prepareStatement("INSERT INTO images VALUES (?, ?)");
ps.setString(1, file.getName());
ps.setBinaryStream(2, fis, file.length());
ps.executeUpdate();
ps.close();
fis.close();

Here, setBinaryStream() transfers a set number of bytes from a stream into the column of type bytea. This also could have been done using the setBytes() method if the contents of the image was already in a byte[].

Retrieving an image is even easier. (We use PreparedStatement here, but the Statement class can equally be used.)

PreparedStatement ps = con.prepareStatement("SELECT img FROM images WHERE imgname = ?");
ps.setString(1, "myimage.gif");
ResultSet rs = ps.executeQuery();
if (rs != null) {
    while (rs.next()) {
        byte[] imgBytes = rs.getBytes(1);
        // use the data in some way here
    }
    rs.close();
}
ps.close();

Here the binary data was retrieved as an byte[]. You could have used a InputStream object instead.

Alternatively you could be storing a very large file and want to use the LargeObject API to store the file:

CREATE TABLE imageslo (imgname text, imgoid oid);

To insert an image, you would use:

// All LargeObject API calls must be within a transaction block
conn.setAutoCommit(false);

// Get the Large Object Manager to perform operations with
LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI();

// Create a new large object
int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE);

// Open the large object for writing
LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE);

// Now open the file
File file = new File("myimage.gif");
FileInputStream fis = new FileInputStream(file);

// Copy the data from the file to the large object
byte buf[] = new byte[2048];
int s, tl = 0;
while ((s = fis.read(buf, 0, 2048)) > 0) {
    obj.write(buf, 0, s);
    tl += s;
}

// Close the large object
obj.close();

// Now insert the row into imageslo
PreparedStatement ps = conn.prepareStatement("INSERT INTO imageslo VALUES (?, ?)");
ps.setString(1, file.getName());
ps.setInt(2, oid);
ps.executeUpdate();
ps.close();
fis.close();

Retrieving the image from the Large Object:

// All LargeObject API calls must be within a transaction block
conn.setAutoCommit(false);

// Get the Large Object Manager to perform operations with
LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI();

PreparedStatement ps = con.prepareStatement("SELECT imgoid FROM imageslo WHERE imgname = ?");
ps.setString(1, "myimage.gif");
ResultSet rs = ps.executeQuery();
if (rs != null) {
    while (rs.next()) {
        // Open the large object for reading
        int oid = rs.getInt(1);
        LargeObject obj = lobj.open(oid, LargeObjectManager.READ);

        // Read the data
        byte buf[] = new byte[obj.size()];
        obj.read(buf, 0, obj.size());
        // Do something with the data read here

        // Close the object
        obj.close();
    }
    rs.close();
}
ps.close();


Posted by 1010
PostgreSQL2016. 3. 11. 17:40
반응형
1
2
3
4
5
6
7
8
9
    WITH UPSERT AS         
    (            
    UPDATE table set             
        name = ''        
    WHERE id= ''        
    RETURNING *        
    )        
    INSERT INTO table(name)
    SELECT ''WHERE NOT EXISTS (SELECT id FROM UPSERT)
cs


Posted by 1010
PostgreSQL2016. 1. 5. 14:39
반응형

PostgreSQL 9.4.0 문서

The PostgreSQL Global Development Group

우리말 옮김: PgDoc 한국어 번역팀


차례
머리말
PostgreSQL이 무엇인가?
PostgreSQL 간추린 역사
일러두기
관련 정보
Bug Reporting Guidelines
I. 자습서
1. 시작하기
2. SQL 언어
3. 고급 기능
II. SQL 언어
4. SQL Syntax
5. Data Definition
6. Data Manipulation
7. Queries
8. Data Types
9. Functions and Operators
10. Type Conversion
11. Indexes
12. Full Text Search
13. 동시성 제어
14. Performance Tips
III. 서버 관리
15. Installation from Source Code
16. Installation from Source Code on Windows
17. 서버 설정 및 운용
18. 서버 환경 설정
19. 클라이언트 인증
20. 데이터베이스 role
21. 데이터베이스 관리
22. 로컬라이제이션
23. 정기적인 데이터베이스 관리 작업들
24. 백업과 복원
25. 고가용성, 부하 분산, 복제
26. 복구 환경설정
27. 데이터베이스 성능 모니터링
28. 디스크 사용량 모니터링
29. 안정성 및 Write-Ahead 로그
30. Regression Tests
IV. 클라이언트 인터페이스
31. libpq - C Library
32. Large Objects
33. ECPG - Embedded SQL in C
34. The Information Schema
V. 서버 프로그래밍
35. Extending SQL
36. Triggers
37. Event Triggers
38. The Rule System
39. Procedural Languages
40. PL/pgSQL - SQL 프로시저 언어
41. PL/Tcl - Tcl Procedural Language
42. PL/Perl - Perl Procedural Language
43. PL/Python - Python Procedural Language
44. Server Programming Interface
45. Background Worker Processes
46. Logical Decoding
VI. 설명서
I. SQL 명령어
II. PostgreSQL 클라이언트 응용프로그램
III. PostgreSQL 서버 응용프로그램
VII. 내부
47. Overview of PostgreSQL Internals
48. System Catalogs
49. Frontend/Backend Protocol
50. PostgreSQL Coding Conventions
51. Native Language Support
52. Writing A Procedural Language Handler
53. Writing A Foreign Data Wrapper
54. Genetic Query Optimizer
55. Index Access Method Interface Definition
56. GiST Indexes
57. SP-GiST Indexes
58. GIN Indexes
59. Database Physical Storage
60. BKI Backend Interface
61. How the Planner Uses Statistics
VIII. 부록
A. PostgreSQL에러 코드
B. Date/Time Support
C. SQL Key Words
D. SQL Conformance
E. Release Notes
F. 부가 확장 모듈들
G. 부가 확장 프로그램들
H. External Projects
I. 소스 코드 저장소
J. 문서 작업
K. Acronyms
참고문헌
색인


Posted by 1010