dongyanhu5628 2013-07-30 05:55
浏览 156
已采纳

MySQL:如何使用HEX将文件存储到中等blob字段二进制文件中

I have wrote a simple VFS (Virtual File System) in PHP (StreamWrapper) that puts it's data into a MySQL database. The field that stores the data is a medium blob.

Things you can do for example in PHP:

copy( 'mytext.txt', 'dbfs://mytext.txt' );
copy( 'mytext.pdf', 'dbfs://mytext.pdf' ); or visa versa/etc.

The problem is binary data such as a pdf to pass thru a SQL statement. Escaping, unquoting, base64 etc ruin the data or take too much memory (overhead), for example base64 takes 3x the space.

The best thing to do is, i think, is make it a hex string (only twice the space) that will be stored in the database as binary (no overhead). I have seen the HEX command of MySQL but can't get it to work like I want.

For example, the next statement does not store it as binary data into the blob:

UPDATE dbfs SET data=0xFF883838<very long string>FFA9999...... WHERE (fid=<number>)

The function I made:

private function writeFile( $fid, &$uData = null, $iFileSize = null )
{ 
 $sSql = 'UPDATE '.self::$dbTableNameFat.
         ' SET data="'.(($uData !== null)?('0x'.bin2hex($uData)):null).'"'.
     ',size="'.((int)$iFileSize).'" WHERE ( fid="'.$fid.'" );';
 return $this->writeQuery( $sSql ); 
}

The blob contains the data but in HEX format and not in binary. How can I achieve the behaviour I want?

  • 写回答

1条回答 默认 最新

  • dongpai1942 2013-07-30 06:16
    关注

    Use a prepared query. I'll use PDO-style syntax.

    private function writeFile($fid, &$uData = null, $iFileSize = null) {
        $stmt = $this->prepare(
            "UPDATE " . self::$dbTableNameFat .
            " SET data = :data, size = :size WHERE fid = :fid");
        $stmt->execute(array( 'data' => $uData,
                              'size' => $iFileSize,
                              'fid' => $fid
                            );
    };
    

    PDO documentation is here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部