MySQL中的二进制数据

时间:2020-03-05 18:37:13  来源:igfitidea点击:

如何在MySQL中存储二进制数据?

解决方案:

对于这样的表:

CREATE TABLE binary_data (
    id INT(4) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    description CHAR(50),
    bin_data LONGBLOB,
    filename CHAR(50),
    filesize CHAR(50),
    filetype CHAR(50)
);

这是一个PHP示例:

<?php
    // store.php3 - by Florian Dittmer <[email protected]>
    // Example php script to demonstrate the storing of binary files into
    // an sql database. More information can be found at http://www.phpbuilder.com/
?>

<html>
    <head><title>Store binary data into SQL Database</title></head>

    <body>
        <?php
            // Code that will be executed if the form has been submitted:

            if ($submit) {
                // Connect to the database (you may have to adjust
                // the hostname, username or password).

                mysql_connect("localhost", "root", "password");
                mysql_select_db("binary_data");

                $data = mysql_real_escape_string(fread(fopen($form_data, "r"), filesize($form_data)));

                $result = mysql_query("INSERT INTO binary_data (description, bin_data, filename, filesize, filetype) ".
                                    "VALUES ('$form_description', '$data', '$form_data_name', '$form_data_size', '$form_data_type')");

                $id= mysql_insert_id();
                print "<p>This file has the following Database ID: <b>$id</b>";

                mysql_close();
            } else {

                // else show the form to submit new data:
        ?>
        <form method="post" action="<?php echo $PHP_SELF; ?>" enctype="multipart/form-data">
            File Description:<br>
            <input type="text" name="form_description"  size="40">
            <input type="hidden" name="MAX_FILE_SIZE" value="1000000">
            <br>File to upload/store in database:<br>
            <input type="file" name="form_data"  size="40">
            <p><input type="submit" name="submit" value="submit">
        </form>

        <?php
            }
        ?>
    </body>
</html>

phpguy的答案是正确的,但我认为那里的其他细节存在很多混乱。

基本答案是在" BLOB"数据类型/属性域中。 BLOB是Binary Large Object的缩写,该列数据类型专用于处理二进制数据。

请参见MySQL的相关手册页。

尽管我们没有说出要存储的内容,但这样做的理由可能很充分,但答案通常是"作为文件系统参考",而实际数据在文件系统中的某个位置。

http://www.onlamp.com/pub/a/onlamp/2002/07/11/MySQLtips.html

还有一个问题是如何将数据放入BLOB。我们可以将数据放在INSERT语句中,如PHP示例所示(尽管我们应该使用mysql_real_escape_string而不是addlashes)。如果文件存在于数据库服务器上,则还可以使用MySQL的LOAD_FILE

虽然没有必要,但是我们可以尝试base64编码数据并解码出来。这意味着数据库将仅具有ascii字符。这将花费更多的时间和空间,但是与二进制数据有关的任何问题都将被消除。

这里提供了更好的存储实现。
我们会遇到Florian的实现问题。

我强烈建议不要在关系数据库中存储二进制数据。关系数据库旨在处理固定大小的数据。那就是它们的性能优势所在:还记得乔尔(Joel)关于数据库为何如此之快的旧文章吗?因为从一条记录移动到另一条记录仅需要1个指针增量。如果添加大小不确定且大小各不相同的BLOB数据,则会提高性能。

而是将文件存储在文件系统中,并将文件名存储在数据库中。

这取决于我们要存储的数据。上面的示例使用了LONGBLOB数据类型,但是我们应该知道还有其他二进制数据格式:

TINYBLOB / BLOB / MEDIUMBLOB / LONGBLOB
VARBINARY
BINARY

每个都有其用例。如果它是已知的(短)长度(例如打包数据),则通常使用" BINARY"或者" VARBINARY"。它们具有能够对它们进行索引的额外好处。