Question

I have images stored in MySQL as blobs (i know it's wrong). And there are many of them. Is there any fast way to drop them all on disk, like SELECT .. INTO OUTFILE, but to many files insted of one? Or the only way is writing a script that will iterate over rows and save images?

Was it helpful?

Solution

Since you want them to be saved into different files on the disk you'll have to go for a script.

OTHER TIPS

#!/usr/bin/perl

#Note: it is my habit to name a Query Result $qR.

use strict;
use DBI;
my $dbh = DBI->connect(YOUR_INFO_HERE);

my $i = 0;
my $q = $dbh->prepare('select image from images');
while (my $qR = $q->fetchrow_arrayref) {
    open(FILE,'>',"$i.jpg");
    print FILE $qR[0];
    close FILE;
    $i++;
}

I had a similar requirement , I found in my case using Java + Hibernate (possibly similar task in other Hibernate variations, but not tried it), got me there quite quickly.

I set up a mapping like this:

<hibernate-mapping>
  <class name="<com.package.table>" table="table">
    <id column="pk" name="pk" type="int">
    </id>
    <property name="blobfield" type="blob"/>
  </class>
</hibernate-mapping>

A Java bean to carry the data, something like:

package com.package;
import java.sql.Blob;
...
public class table {
...
public Blob getBlobfield {
...

And a loop something like this:

 ...
 tx = session.beginTransaction();
 Criteria crit = session.createCriteria(table.class);
 crit.setMaxResults(50); // Alter this to suit...
           List<table> rows = crit.list();
           for (table r: rows) {
               ExtractBlob(r.getId(), r.getBlobField);
 }

And something ("ExtractBlob" is I'm calling this) to extract the blob (using the PK to generate a filename), something like this:

...

 FileOutputStream fout=new FileOutputStream(<...base output file on PK for example...>
 BufferedOutputStream bos=new BufferedOutputStream(fout);
 InputStream is=blob.getBinaryStream();
 byte[] b=new byte[8192];
 while ( (is.read(b))>0 ) {
       bos.write(b);
 }
 is.close();
 bos.close()

;

...

I can post a more complete example if you looks like it might be useful - but I would have extract the code from a bigger project, otherwise I would have just posted it straight up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top