Save/Write/Read image file from/to a database using Java program
By: Issac
Assuming you have a table with a blob field and you want to save a file and store it in the database table or you want to read from a blob object stored in a database, you can use these below java code snippets to write file and read file from database.
The sample table is created as below to have a blob field to store file.
CREATE TABLE t1 (c1 INT PRIMARY KEY NOT NULL, c2 BLOB(5M));
Then use the below code snippet to insert an image file as
follows.
PreparedStatement pstmt = conn.prepareStatement ("INSERT
INTO t1 VALUES (?,?)");
pstmt.setInt (1, 100);
File fBlob = new File (
"image1.gif" );
FileInputStream is = new FileInputStream ( fBlob
);
pstmt.setBinaryStream (2, is, (int) fBlob.length() );
pstmt.execute
();
...
Retrieving a BLOB or in other words retrieving the image
file stored in the database as follows:
Statement stmt =
conn.createStatement ();
ResultSet rs= stmt.executeQuery("SELECT * FROM
t1");
while(rs.next()) {
int val1 = rs.getInt(1);
InputStream val2 =
rs.getBinaryStream(2);
...
} rs.close();
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Archived Comments
1. Ezequiel
View Tutorial By: free java games at 2012-06-26 17:21:34
2. nice explanation.but one thing in retrieving proce
View Tutorial By: venkateswarlu at 2013-04-06 09:03:46