Powered by Ajaxy
Digg StumbleUpon LinkedIn YouTube Flickr Facebook Twitter RSS Reset

Java: insert image into database

Java: insert image into database
{filelink=7035}

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.BatchUpdateException;
public class BD_Image
 {
  public static void main(String[] args)throws Exception
  {
   System.out.println ("1");
   Connection conn=null;
   FileInputStream fis = null;
   	    System.out.println ("2");
  try {
  	   System.out.println ("3");
   conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=Cours",
        "user", "");
    conn.setAutoCommit(false);
    	   System.out.println ("4");
   System.out.println ("connexion reussi");
    String req = "INSERT INTO Test (name, price, image) VALUES (?, ?, ?)";
    PreparedStatement pstmt = conn.prepareStatement(req);
      File image = new File("D:/logo.gif");
      fis = new FileInputStream(image);
      pstmt.setString(1, "mon Nom");
      pstmt.setInt(2, 1500);
      // insert image
      pstmt.setBinaryStream(3, fis, (int) image.length());
      pstmt.executeUpdate();
      conn.commit();
  } catch(Exception ex)
     {
     	conn.rollback();
     	ex.printStackTrace();
     }
     finally {
      conn.close();
      fis.close();
    }
  }
}

Users who found this page were searching for:

  • java source how to insert an image into database
  • java insert image into database using java statement
  • python compare strings

No comments yet.

Leave a Comment