On Feb 27, 2008, at 4:48 PM, Mike McGonagle wrote:

> Hello all,
> I was hoping that someone might share some tips on working with  
> Blobs? I
> would like to be able to store some images and sound files in a  
> database,
> but never having dealt with them, I am kind of at a loss for some  
> examples.
> I have looked on the web, and there are few examples that were of use.

Well, I wrote a quick and dirty program for stuffing image files into  
a database. You just provide a directory and it stats() each file,  
allocates enough space for the image data, then loads it from disk.  
Sql statement is something like:

char* sql = "insert into i (name, data) values (?, ?);";

Of course if your images are huge this method coud be problematic. I  
believe SQLite supports an incremental way to do this but I haven't  
looked at those calls yet.

    while ( (dentry = readdir(dir)) != '\0') {
       if (dentry->d_name[0] == '.')
          continue;

       if (fd != -1) {
          close(fd);
          fd = -1;
       }

       if (data != '\0') {
          free(data);
          data = '\0';
       }

       snprintf(fname, sizeof(fname), "%s/%s", newdir, dentry->d_name);
       stat(fname, &sb);

       if ( (data = malloc(sb.st_size)) == '\0') {
          fprintf(stderr, "malloc() failed\n");
          sqlite3_finalize(stmt);
          sqlite3_close(db);
          exit(1);
       }

       if ( (fd = open(fname, O_RDONLY, 0000)) == -1) {
          fprintf(stderr, "open() failed\n");
          sqlite3_finalize(stmt);
          sqlite3_close(db);
          exit(1);
       }

       if ( (retval = read(fd, data, sb.st_size)) == -1) {
          fprintf(stderr, "read() failed\n");
          sqlite3_finalize(stmt);
          sqlite3_close(db);
          exit(1);
       }

       if (retval != sb.st_size) {
          fprintf(stderr, "read() failed\n");
          sqlite3_finalize(stmt);
          sqlite3_close(db);
          exit(1);
       }

       rc = sqlite3_bind_text(stmt, 1, dentry->d_name, dentry->d_namlen,
                              SQLITE_STATIC);

       if (rc != SQLITE_OK) {
          fprintf(stderr, "sqlite3_bind_text() %s\n", sqlite3_errmsg 
(db));
          sqlite3_finalize(stmt);
          sqlite3_close(db);
          exit(1);
       }

       rc = sqlite3_bind_blob(stmt, 2, data, sb.st_size, SQLITE_STATIC);

       if (rc != SQLITE_OK) {
          fprintf(stderr, "sqlite3_bind_blob() %s\n", sqlite3_errmsg 
(db));
          sqlite3_finalize(stmt);
          sqlite3_close(db);
          exit(1);
       }

       rc = sqlite3_step(stmt);

       if (rc != SQLITE_DONE) {
          fprintf(stderr, "sqlite3_step() %s\n", sqlite3_errmsg(db));
          sqlite3_finalize(stmt);
          sqlite3_close(db);
          exit(1);
       }

       sqlite3_reset(stmt);
    }

_______________________________________________
sqlite-users mailing list
sqlite-users@sqlite.org
http://sqlite.org:8080/cgi-bin/mailman/listinfo/sqlite-users

Reply via email to