首页 >后端开发 >C++ >将文件作为字节数组存储在数据库中是最有效的方法吗?

将文件作为字节数组存储在数据库中是最有效的方法吗?

Susan Sarandon
Susan Sarandon原创
2025-01-15 09:31:48504浏览

Is Storing Files as Byte Arrays in a Database the Most Efficient Method?

将任何格式的文件作为字节数组存储到数据库中

将各种格式的文件保存到数据库或磁盘需要仔细考虑。一种常见的方法是在存储之前将文件转换为字节数组。此方法允许存储任何格式的文件,但它提出了一个问题,即它是否是最佳方法。

为了说明这个过程,请考虑答案中提供的以下代码片段:

将文件作为字节数组插入 SQL Server 数据库:

<code class="language-c#">public static void databaseFilePut(string varFilePath) {
    byte[] file;
    using (var stream = new FileStream(varFilePath, FileMode.Open, FileAccess.Read)) {
        using (var reader = new BinaryReader(stream)) {
            file = reader.ReadBytes((int) stream.Length);       
        }          
    }
    using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
    using (var sqlWrite = new SqlCommand("INSERT INTO Raporty (RaportPlik) Values(@File)", varConnection)) {
        sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file;
        sqlWrite.ExecuteNonQuery();
    }
}</code>

从数据库中检索文件作为字节数组:

<code class="language-c#">public static MemoryStream databaseFileRead(string varID) {
    MemoryStream memoryStream = new MemoryStream();
    using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
    using (var sqlQuery = new SqlCommand(@"SELECT [RaportPlik] FROM [dbo].[Raporty] WHERE [RaportID] = @varID", varConnection)) {
        sqlQuery.Parameters.AddWithValue("@varID", varID);
        using (var sqlQueryResult = sqlQuery.ExecuteReader())
            if (sqlQueryResult != null) {
                sqlQueryResult.Read();
                byte[] blob = new byte[(int)sqlQueryResult.GetBytes(0, 0, null, 0, int.MaxValue)];
                sqlQueryResult.GetBytes(0, 0, blob, 0, blob.Length);
                memoryStream.Write(blob, 0, blob.Length);
            }
    }
    return memoryStream;
}</code>

使用 MemoryStream 将文件作为字节数组插入数据库:

<code class="language-c#">public static int databaseFilePut(MemoryStream fileToPut) {
        int varID = 0;
        byte[] file = fileToPut.ToArray();
        const string preparedCommand = @"
                    INSERT INTO [dbo].[Raporty]
                               ([RaportPlik])
                         VALUES
                               (@File)
                        SELECT [RaportID] FROM [dbo].[Raporty]
            WHERE [RaportID] = SCOPE_IDENTITY()
                    ";
        using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetails))
        using (var sqlWrite = new SqlCommand(preparedCommand, varConnection)) {
            sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file;

            using (var sqlWriteQuery = sqlWrite.ExecuteReader())
                while (sqlWriteQuery != null && sqlWriteQuery.Read()) {
                    varID = sqlWriteQuery["RaportID"] is int ? (int) sqlWriteQuery["RaportID"] : 0;
                }
        }
        return varID;
    }</code>

这些代码片段演示了将文件转换为字节数组的过程,然后将其存储在 VARBINARY(MAX) 类型的数据库列中。需要时,可以将文件检索为字节数组,并保存为新文件或流式传输到应用程序中。

The provided text is already quite concise and well-written. The primary change made is to correct a minor issue in the databaseFileRead function where the byte array length was not correctly cast to an integer before allocation. No other significant alterations were deemed necessary for effective paraphrasing while maintaining the original meaning and structure.

以上是将文件作为字节数组存储在数据库中是最有效的方法吗?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn