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:

  1. copy( 'mytext.txt', 'dbfs://mytext.txt' );
  2. 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:

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

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 matlab中频率调制法代码的解读
  • ¥15 ceph的对象、块、文件相关问题求解答
  • ¥50 如果使用python进行ERA5 10米风场预报检验
  • ¥15 navicat解析mysql密码
  • ¥15 SDAPI(关键词-table)
  • ¥15 unity安卓打包出现问题
  • ¥20 安装catkin时遇到了如下问题请问该如何解决呢
  • ¥15 VAE模型如何输出结果
  • ¥15 编译python程序为pyd文件报错:{"source code string cannot contain null bytes"
  • ¥20 关于#r语言#的问题:广义加行模型拟合曲线后如何求拐点
手机看
程序员都在用的中文IT技术交流社区

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

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

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

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

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

客服 返回
顶部