Example to store image
in Oracle database
You can store images in the database in java by
the help of PreparedStatement interface.
The setBinaryStream() method of
PreparedStatement is used to set Binary information into the parameterIndex.
Signature of setBinaryStream method
The syntax of setBinaryStream() method is given
below:
1. 1) public void setBinaryStream(int paramIndex,InputStream stream)
2. throws SQLException
3. 2) public void setBinaryStream(int paramIndex,InputStream stream,long length)
4. throws SQLException
For storing image into the database, BLOB
(Binary Large Object) datatype is used in the table. For example:
1. CREATE TABLE "IMGTABLE"
2. ( "NAME" VARCHAR2(4000),
3. "PHOTO" BLOB
4. )
5. /
Let's write the jdbc code to store the image in
the database. Here we are using d:\\d.jpg for the location of image. You can
change it according to the image location.
1. import java.sql.*;
2. import java.io.*;
3. public class InsertImage {
4. public static void main(String[] args) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection(
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=con.prepareStatement("insert into imgtable values(?,?)");
11. ps.setString(1,"sonoo");
12.
13. FileInputStream fin=new FileInputStream("d:\\g.jpg");
14. ps.setBinaryStream(2,fin,fin.available());
15. int i=ps.executeUpdate();
16. System.out.println(i+" records affected");
17.
18. con.close();
19. }catch (Exception e) {e.printStackTrace();}
20. }
21. }
If you see the table, record is stored in the
database but image will not be shown. To do so, you need to retrieve the image
from the database which we are covering in the next page.
No comments:
Post a Comment