데이터베이스에 저장된 파일을 열기 위해서는 해당 파일을 먼저 로컬 컴퓨터에 다운로드해야 합니다. 다운로드한 후에는 앞서 언급한 방법과 마찬가지로 Desktop 클래스와 File 클래스를 사용하여 파일을 실행할 수 있습니다.
여기에는 몇 가지 예시가 있습니다.
- JDBC를 사용하여 데이터베이스에서 파일 다운로드하기
import java.io.*; import java.sql.*; public class DownloadFileFromDatabase { public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "username", "password"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT file FROM mytable WHERE id = 1"); if (rs.next()) { Blob blob = rs.getBlob("file"); InputStream in = blob.getBinaryStream(); OutputStream out = new FileOutputStream("myfile.txt"); byte[] buffer = new byte[1024]; int length = -1; while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); } in.close(); out.close(); Desktop.getDesktop().open(new File("myfile.txt")); } rs.close(); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
이 예제는 JDBC를 사용하여 MySQL 데이터베이스에서 mytable 테이블의 id가 1인 레코드의 file 필드에 저장된 파일을 다운로드하고 실행하는 방법을 보여줍니다. 다운로드된 파일은 myfile.txt로 저장됩니다.
- JPA를 사용하여 데이터베이스에서 파일 다운로드하기
import java.io.*; import javax.persistence.*; public class DownloadFileFromDatabase { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("mydatabase"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); MyEntity entity = em.find(MyEntity.class, 1); if (entity != null) { Blob blob = entity.getFile(); InputStream in = blob.getBinaryStream(); OutputStream out = new FileOutputStream("myfile.txt"); byte[] buffer = new byte[1024]; int length = -1; while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); } in.close(); out.close(); Desktop.getDesktop().open(new File("myfile.txt")); } tx.commit(); em.close(); emf.close(); } }
이 예제는 JPA를 사용하여 MyEntity 엔티티의 id가 1인 레코드의 file 필드에 저장된 파일을 다운로드하고 실행하는 방법을 보여줍니다. 다운로드된 파일은 myfile.txt로 저장됩니다. persistence.xml 파일에는 데이터베이스 연결 정보와 MyEntity 클래스와 매핑되는 정보가 포함되어 있어야 합니다.
'Temp' 카테고리의 다른 글
레노버 화면이 안 나올 때 해결 방법! 노트북 화면 고장을 스스로 고쳐보세요 (0) | 2023.03.03 |
---|---|
갤럭시 데이터 속도 느림 방법 알려드립니다. (0) | 2023.03.03 |
마인크래프트 스크립트 플레이어 움직임 탐지 (0) | 2023.03.01 |
Windows 활성화 에러 해결하기: 인터넷 연결부터 Microsoft Support까지 (0) | 2023.03.01 |
아이폰 벨소리와 알람 볼륨을 따로 설정하는 방법! 쉽고 간단하게 알려드립니다 (0) | 2023.03.01 |
댓글