How do I insert an image file into a database?

How do I insert an image file (or other raw data) into a database?

Upload all raw data-types (like binary documents) to the database as an array of bytes (bytes[]). Then you can,

1. Read all data from the file using a FileInputStream,
2. Create a byte array from the read data,
3. Use method setBytes(int index, byte[] data) of java.sql.PreparedStatement to upload the data.

How do I insert an image file (or other raw data) into a database? Explain with an example.

The following is the code to create table in jdbc
public void createConnection()
{
   try
   {
       //use your own userid,password and datasorce
       connstr="User Id="userid ";Password="password" ;Data Source="datasource ";";
       conn=new OracleConnection(connstr);
       conn.Open();
       OracleCommand cmnd=conn.CreateCommand();
       cmnd.CommandText="CREATE TABLE emp(id INTEGER,name
VARCHAR2 (50),photo BLOB)";
       cmnd.ExecuteNonQuery();
   }
   catch(Exception e)
   {
       MessageBox.Show(e.Message);
   }
}
The .jpg image file path can be given by using fileOpenDialog() method. The .jpg image file is then converted into a bitmap image and stored. To insert an image into the blob field, use FileStream object. Use read method to read the image and store in an array of byte type. Insert the byte array into the blob field using ‘insert’ statement of sql.
PreparedStatement - advantages of PreparedStatement
PreparedStatement - What is PreparedStatement?, What is the advantage of using a Prepared Statement?, difference between Statement and Prepared Statement...
Difference between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE
TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE - Constant indicating that the type for a ResultSet object is scrollable but not sensitive to changes made by others...
Different types of RowSet
JDBC RowSet Types - Connected: A connected RowSet Object is permanent in nature. It doesn’t terminate until the application is terminated...
Post your comment