ابدأ بالتواصل مع الأشخاص وتبادل معارفك المهنية

أنشئ حسابًا أو سجّل الدخول للانضمام إلى مجتمعك المهني.

متابعة

How to insert and retrieve image from MySQL (DB) to Java?

user-image
تم إضافة السؤال من قبل Usama Saad , Senior Software Engineer (Java) , Saudi Catering Company
تاريخ النشر: 2013/08/18
Usama Saad
من قبل Usama Saad , Senior Software Engineer (Java) , Saudi Catering Company

I will answer this question using demo consist of3 steps :   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); refrence http://usama-saad.blogspot.com/2013/07/how-to-insert-and-retrieve-image-from.html

Salman Mansoor
من قبل Salman Mansoor , Digital Strategist / Social Media Strategist , RockSol | Digital Creative Agency | Software House

You can use blob datatype for your image.Here is the sample link for your requirements.And the other way is changing image into byte data and store it into your database with byte datatype.But I personally not recommended storing image into database

المزيد من الأسئلة المماثلة

هل تحتاج لمساعدة في كتابة سيرة ذاتية تحتوي على الكلمات الدلالية التي يبحث عنها أصحاب العمل؟