C++/CLI Code Snippet - Insert/Update Image To SQL Server

C++/CLI Code Snippet - Insert/Update Image To SQL Server

C++/CLI Code Snippet - Insert/Update Image To SQL Server

C++/CLI code snippet connects to SQL server and executes SQL statement and update/insert binary image data in database table. InsertUpdateImage update/insert image into database using open database connection, insert/update SQL statement, binary image and image format.

Bookmark:

C++/CLI Code Snippet - Insert/Update Image To SQL Server

This .Net C++/CLI code snippet connects to SQL server and executes SQL statement and update/insert binary image data in database table. To use this function simply provide open database connection, insert/update SQL statement, binary image and image format. This function uses SqlClient name space to update data using SqlCommand. Modify the exception handling section to as your project requirements.

int InsertUpdateImage(System::Data::SqlClient::SqlConnection ^%_SqlConnection, System::String ^_SQL, System::Drawing::Image ^_Image, System::String ^_ImageFieldName, System::Drawing::Imaging::ImageFormat ^_ImageFormat)
{
    int _SqlRetVal = 0;

    try
    {
        // lets add this record to database
        System::Data::SqlClient::SqlCommand ^_SqlCommand = gcnew System::Data::SqlClient::SqlCommand(_SQL, _SqlConnection);

        // Convert image to memory stream
        System::IO::MemoryStream ^_MemoryStream = gcnew System::IO::MemoryStream();
        _Image->Save(_MemoryStream, _ImageFormat);

        // Add image as SQL parameter
        System::Data::SqlClient::SqlParameter ^_SqlParameter = gcnew System::Data::SqlClient::SqlParameter("@" + _ImageFieldName, SqlDbType::Image);

        _SqlParameter->Value = _MemoryStream->ToArray();
        _SqlCommand->Parameters->Add(_SqlParameter);

        // Executes a Transact-SQL statement against the connection 
        // and returns the number of rows affected.
        _SqlRetVal = _SqlCommand->ExecuteNonQuery();

        // Dispose command
        delete _SqlCommand;
        _SqlCommand = nullptr;
    }
    catch (Exception ^_Exception)
    {
        // Error occurred while trying to execute reader
        // send error message to console (change below line to customize error handling)
        Console::WriteLine(_Exception->Message);

        return 0;
    }

    return _SqlRetVal;
}


Here is a simple example showing how to use above function (InsertUpdateImage) to load new image from file and insert into database table.

// set temporary variable for database connection
System::Data::SqlClient::SqlConnection ^_SqlConnection = gcnew System::Data::SqlClient::SqlConnection();

// assign database connection string
_SqlConnection->ConnectionString = "Server=SERVERADDRESS;Database=DATABASENAME;Uid=USERID;Pwd=PASSWORD;";

// Connect to database
try
{
    _SqlConnection->Open();
}
catch (Exception ^_Exception)
{
    // Error occurred while trying to connect to database
    Console::WriteLine(_Exception->Message);
}

// Check for valid open database connection before query database
if (_SqlConnection != nullptr && _SqlConnection->State == ConnectionState::Open)
{
    int _RecCount = 0;

    // load image from file
    System::Drawing::Image ^_Image = System::Drawing::Image::FromFile("C:\\SampleImage.JPG");

    // add new record to database table and get the autoincrement product id
        // Pass open database connection to function
        // Pass SQL statement to insert new record
        // pass image
        // image field name
        // image format
    _RecCount = InsertUpdateImage(_SqlConnection, "INSERT INTO sampletable (name, price, image) VALUES ('sample product name', 22.75, @image)", _Image, "image", System::Drawing::Imaging::ImageFormat::Jpeg);

    if (_RecCount > 0)
    {
        // Record successfully insert into database
        Console::WriteLine("Image Record added to database table");
    }
    else
    {
        // Record failed to insert into database
        Console::WriteLine("Failed to add new record to database table");
    }

    // close database connection
    _SqlConnection->Close();
}


C++/CLI Keywords Used:

  • byte
  • Image
  • ImageFormat
  • SqlDbType::Image
  • MemoryStream
  • ExecuteNonQuery
  • SqlConnection
  • ConnectionString
  • SqlCommand
  • Exception

Code Snippet Information:

  • Applies To: .Net, C++, CLI, SQL, SqlCommand, ExecuteNonQuery, MemoryStream, Image, ImageFormat, SqlDbType, SQL Server, SQL Client, Connection String, Database Connection, SQL Server Binary Data
  • Programming Language : C++/CLI

External Resources:

Leave a comment