2011-01-10 184 views
20

我有一张表格,图像数据存储在MySQL数据库的blob字段中。有没有办法通过仅使用SQL将这些图像导出到文件系统上的文件?这些图片应该命名为{imageId} .jpg从MySQL数据库导出Blob到只有SQL的文件

我知道使用Java或其他方法很容易做到这一点,但只需要一个SQL脚本就可以做到这一点?

+0

这可能取决于用户MySQL是否运行在有文件系统的写访问权限。 – 2011-01-10 12:03:44

+0

当然,但它甚至有可能吗?因为我还没有看过SQL命令来访问fielsystem – suicide 2011-01-10 12:12:00

回答

12

我不喜欢这个主意......

drop procedure if exists dump_image; 
delimiter // 
    create procedure dump_image() 
    begin 

    declare this_id int; 
    declare cur1 cursor for select imageId from image; 
    open cur1; 
     read_loop: loop 
     fetch cur1 into this_id; 
     set @query = concat('select blob_field from image where imageId=', 
      this_id, ' into outfile "/tmp/xyz-', this_id,'.jpg"'); 
     prepare write_file from @query; 
     execute write_file; 
     end loop; 
    close cur1; 
    end // 
delimiter ; 

尽管错误

 
mysql> call dump_image(); 
ERROR 1329 (02000): No data - zero rows fetched, selected, or processed 
ls -1 /tmp/xyz*
+0

你在哪里设置了`this_id`?你没有传入任何东西,它没有在proc中设置,所以查询将失败。否则,这看起来像它会工作 – 2011-01-10 12:50:24

15

假设你有写权限的用户mysql中的位置要存储的文件,你可以这样做:

Select id,blob into dumpfile '/tmp/path' from table; 

不幸的是,在MySQL中不可能将转储文件指定为表达式/变量。但是,如果将其包装在存储过程中并使用变量,则可以实现此目的。

相关问题