【发布时间】:2016-05-06 16:48:10
【问题描述】:
我的问题:如何在 Windows 窗体应用程序中使用 c++ 将文件存储在 sql server 中?
我的问题:我正在从文件中读取二进制数据,然后打开与 SQL Server 2014 的连接。当我将我的 sql 命令与二进制数据一起发送到数据库时,我收到一条错误消息“无法转换参数值从一个字节到一个字节[]。”。我看到很多人在 C# 应用程序中使用这种方法。我该如何适应 c++?
我的代码:
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
}
【问题讨论】:
-
我认为问题在于“binaryData”是一个数组,而您使用它就像一个变量。尝试在你的演员表中使用 &binaryData[0]。
-
将其更改为“data = gcnew System::Byte(reinterpret_cast
(&binaryData[0]));”还是不行。它对待它的方式相同,我收到相同的错误消息。
标签: c++ sql winforms byte varbinarymax