here is a few steps to insert and retrieve image files from DB.
the image column will save a file , so it's recommend to make its type blob.
Ex :
CREATE TABLE `mydb`.`tablename` (
`id` INT NOT NULL AUTO_INCREMENT ,
`image` BLOB NULL ,
`image_name` VARCHAR(45) NULL ,
PRIMARY KEY (`id`) );
.
To handle retrieving Image in easy way . you can do below code in steps after line 5
Click here to download full Demo.
1. Creating the Image column:
the image column will save a file , so it's recommend to make its type blob.
Ex :
CREATE TABLE `mydb`.`tablename` (
`id` INT NOT NULL AUTO_INCREMENT ,
`image` BLOB NULL ,
`image_name` VARCHAR(45) NULL ,
PRIMARY KEY (`id`) );
2. Java code to insert Image :
- File image = new File("c:/Me.jpg");
- psmnt = connection.prepareStatement("insert into tablename (image , image_name) " + "values(? ,?)");
- fis = new FileInputStream(image);
- psmnt.setBinaryStream(1, (InputStream) fis, (int) (image.length()));
- psmnt.setString(2,image.getName());
- psmnt.executeUpdate();
3. Retrieve file from db :
- rs = stmt.executeQuery("SELECT image , image_name FROM tablename ");
- String filename = "";
- while (rs.next()) {
- filename = rs.getString(2);
- Blob test = rs.getBlob("image");
- InputStream x = test.getBinaryStream();
- int size = x.available();
- OutputStream out = new FileOutputStream("c:/"+filename);
- byte b[] = new byte[size];
- x.read(b);
- out.write(b);
- }
.
To handle retrieving Image in easy way . you can do below code in steps after line 5
- byte[] image = rs.getBytes("image")
- Image img = Toolkit.getDefaultToolkit().createImage(image);
- ImageIcon icon = new ImageIcon(img);
Click here to download full Demo.
No comments:
Post a Comment