Share via


Scrittura di valori BLOB in un database

È possibile scrivere un oggetto binario di grandi dimensioni (BLOB, Binary Large Object) in un database come dati binari o come dati di tipo carattere, a seconda del tipo di campo dell'origine dati. Per scrivere un valore BLOB nel database, eseguire l'istruzione INSERT o UPDATE appropriata e passare il valore BLOB come parametro di input (vedere Utilizzo di stored procedure con un comando). Se il BLOB è memorizzato come testo, come nel caso di un campo text di SQL Server, sarà possibile passarlo come parametro di stringa. Se il BLOB è memorizzato in formato binario, come nel caso di un campo image di SQL Server, sarà possibile passare una matrice di tipo byte come parametro binario.

Nota   È possibile che il BLOB presenti considerevoli dimensioni e che la sua memorizzazione come valore singolo comporti un consistente impiego della memoria di sistema, con la conseguente riduzione delle prestazioni dell'applicazione. Per ridurre la quantità di memoria utilizzata durante la scrittura di un valore BLOB, è possibile scrivere il BLOB nel database in "blocchi". Il processo attraverso cui un BLOB viene scritto in un database in questo modo dipende dalle caratteristiche dell'origine dati. Per un esempio di scrittura in "blocchi" di un valore BLOB in SQL Server, vedere Riduzione dell'impiego di risorse durante la scrittura di valori BLOB in SQL Server.

Nell'esempio di codice che segue vengono aggiunte informazioni relative agli impiegati nella tabella Employees del database Northwind. Una foto dell'impiegato viene letta da un file e aggiunta a un campo di tipo image della tabella, denominato Photo.

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO

Public Class EmployeeData

  Public Shared Sub Main()
    Dim hireDate As DateTime = DateTime.Parse("5/21/99")
    AddEmployee("Jones", "Mary", "Sales Representative", hireDate, 5, "jones.bmp")
  End Sub

  Public Shared Sub AddEmployee(lastName As String, firstName As String, title As String, hireDate As DateTime, _
                                reportsTo As Integer, photoFilePath As String)

    Dim photo() as Byte = GetPhoto(photoFilePath)

    Dim nwindConn As SqlConnection = New SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;")

    Dim addEmp As SqlCommand = New SqlCommand("INSERT INTO Employees (LastName, FirstName, Title, HireDate, ReportsTo, Photo) " & _
                                              "Values(@LastName, @FirstName, @Title, @HireDate, @ReportsTo, @Photo)", nwindConn) 

    addEmp.Parameters.Add("@LastName",  SqlDbType.NVarChar, 20).Value = lastName
    addEmp.Parameters.Add("@FirstName", SqlDbType.NVarChar, 10).Value = firstName
    addEmp.Parameters.Add("@Title",     SqlDbType.NVarChar, 30).Value = title
    addEmp.Parameters.Add("@HireDate",  SqlDbType.DateTime).Value     = hireDate
    addEmp.Parameters.Add("@ReportsTo", SqlDbType.Int).Value          = reportsTo

    addEmp.Parameters.Add("@Photo",     SqlDbType.Image, photo.Length).Value = photo

    nwindConn.Open()

    addEmp.ExecuteNonQuery()

    nwindConn.Close()
  End Sub

  Public Shared Function GetPhoto(filePath As String) As Byte()
    Dim fs As FileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)
    Dim br As BinaryReader = new BinaryReader(fs)

    Dim photo() As Byte = br.ReadBytes(fs.Length)

    br.Close()
    fs.Close()

    Return photo
  End Function
End Class
[C#]
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;

public class EmployeeData
{
  public static void Main()
  {
    DateTime hireDate = DateTime.Parse("5/21/99");
    AddEmployee("Jones", "Mary", "Sales Representative", hireDate, 5, "jones.bmp");
  }

  public static void AddEmployee(string lastName, string firstName, string title, DateTime hireDate , int reportsTo, string photoFilePath)
  {
    byte[] photo = GetPhoto(photoFilePath);

    SqlConnection nwindConn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;");

    SqlCommand addEmp = new SqlCommand("INSERT INTO Employees (LastName, FirstName, Title, HireDate, ReportsTo, Photo) " +
                                       "Values(@LastName, @FirstName, @Title, @HireDate, @ReportsTo, @Photo)", nwindConn); 

    addEmp.Parameters.Add("@LastName",  SqlDbType.NVarChar, 20).Value = lastName;
    addEmp.Parameters.Add("@FirstName", SqlDbType.NVarChar, 10).Value = firstName;
    addEmp.Parameters.Add("@Title",     SqlDbType.NVarChar, 30).Value = title;
    addEmp.Parameters.Add("@HireDate",  SqlDbType.DateTime).Value     = hireDate;
    addEmp.Parameters.Add("@ReportsTo", SqlDbType.Int).Value          = reportsTo;

    addEmp.Parameters.Add("@Photo",     SqlDbType.Image, photo.Length).Value = photo;

    nwindConn.Open();

    addEmp.ExecuteNonQuery();

    nwindConn.Close();
  }

  public static byte[] GetPhoto(string filePath)
  {
    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
    BinaryReader br = new BinaryReader(fs);

    byte[] photo = br.ReadBytes((int)fs.Length);

    br.Close();
    fs.Close();

    return photo;
  }
}

Vedere anche

Utilizzo di provider di dati .NET Framework per accedere ai dati | Recupero di valori BLOB da un database | Classe OleDbCommand | Classe OdbcCommand | Classe SqlCommand