Home > Backend Development > C++ > Is Storing Files as Byte Arrays in a Database the Optimal Approach for Diverse File Types?

Is Storing Files as Byte Arrays in a Database the Optimal Approach for Diverse File Types?

Barbara Streisand
Release: 2025-01-15 11:31:44
Original
111 people have browsed it

Is Storing Files as Byte Arrays in a Database the Optimal Approach for Diverse File Types?

Best way to store database files: Convert file to byte array?

Question:

Is converting all file formats to byte arrays the best solution for database or disk storage? Is this approach the best, especially when dealing with multiple file types such as GIF, DOC or PDF?

Answer:

Assuming the target database is SQL Server, this solution can effectively handle SQL Server 2005 and 2008. The following steps outline the process:

  1. Create database table: Create a table with a VARBINARY(MAX) column for storing binary data. In this example, create a table called "Raporty" that contains a VARBINARY(MAX) type column called "RaportPlik".

  2. Method to save files to database:

    <code class="language-csharp">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>
    Copy after login
  3. Methods to retrieve and save files from the database:

    <code class="language-csharp">public static void databaseFileRead(string varID, string varPathToNewLocation) {
        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();
                    var blob = new Byte[(sqlQueryResult.GetBytes(0, 0, null, 0, int.MaxValue))];
                    sqlQueryResult.GetBytes(0, 0, blob, 0, blob.Length);
                    using (var fs = new FileStream(varPathToNewLocation, FileMode.Create, FileAccess.Write)) 
                        fs.Write(blob, 0, blob.Length);
                }
        }
    }</code>
    Copy after login
  4. Method to retrieve file as MemoryStream:

    <code class="language-csharp">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();
                    var blob = new Byte[(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>
    Copy after login
  5. Method to save MemoryStream to database:

    <code class="language-csharp">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>
    Copy after login

With these methods, you can efficiently store and retrieve files of various formats in SQL Server database. This method provides a simple and reliable solution for managing binary data.

The above is the detailed content of Is Storing Files as Byte Arrays in a Database the Optimal Approach for Diverse File Types?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template