MY QUESTION: how do I store a file in a sql server using c++ from a windows form application?
MY PROBLEM: I am reading in binary data from a file then opening a connection to a SQL Server 2014. When I send my sql command to the database with the binary data, I get an error message "Failed to convert parameter value from a Byte to a Byte[].". I see many people using this method in C# applications. How do I adapt this for c++?
MY CODE:
void AddFileToDatabase() {
unsigned char* binaryData; // holds the files binary data
int sizeOfBinaryData = 0; // the size of binaryData in bytes
// Open the test file in binary mode and read the contents into 'binaryData'
std::ifstream inFile("a.txt", std::ios::in | std::ios::binary); // open the test file 'a.txt'
if(inFile.is_open()) {
inFile.seekg(0,std::ios::end); // move to the end of the file
sizeOfBinaryData = (int)inFile.tellg(); // get the file size
inFile.seekg(0,std::ios::beg); // move to the start of the file
binaryData = new unsigned char[sizeOfBinaryData]; // create space for the binary data
inFile.read((char*)binaryData,sizeOfBinaryData); // read in the binary data
inFile.close(); // close the file
}
// Connect to the database
System::Data::SqlClient::SqlConnection^ Connection = gcnew System::Data::SqlClient::SqlConnection("server=MYserver,MYport;Integrated security=SSPI;Database=MYdatabase;"); // create a connection to the database
Connection->Open(); // open the connection to the database
// Setup the sql command
System::Data::SqlClient::SqlCommand^ Command = gcnew System::Data::SqlClient::SqlCommand("INSERT INTO MYtable VALUES(@binaryValue);", Connection); // create the sql command (the column type in MYtable is 'varbinary(MAX)')
System::Byte^ data = gcnew System::Byte(reinterpret_cast<unsigned char>(binaryData)); // store the binary data in a System::Byte type so the sql Command will accept it as a parameter
Command->Parameters->Add("@binaryValue", System::Data::SqlDbType::VarBinary, sizeOfBinaryData)->Value = data; // add the binary data to the sql command
// Attempt to insert the binary data into the database
try {
Command->ExecuteNonQuery(); // insert binay data into database
System::Windows::Forms::MessageBox::Show("IT WORKED!!!","Success", System::Windows::Forms::MessageBoxButtons::OK,System::Windows::Forms::MessageBoxIcon::Information); // tell us if we are big winners
}
catch(System::Exception^ ex) {
System::Windows::Forms::MessageBox::Show(ex->Message,"Error", System::Windows::Forms::MessageBoxButtons::OK,System::Windows::Forms::MessageBoxIcon::Error); // tell us why we failed
}
delete[] binaryData; // clean up
}