dongyanhu5628 2013-07-30 13:55
浏览 154
已采纳

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 14: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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料