版权声明:欢迎评论和转载,转载请注明来源。 https://blog.csdn.net/zy332719794/article/details/7407158
写入本地文件到数据库
void DlgImpRoadSection::OnOkBtnClicked()
{
#pragma region 验证
CString tempStr;
CString fileName;
m_FilePath.GetWindowText(fileName);
if (access((const char*)_bstr_t(fileName), 0) != 0)
{
ads_alert(L"文件不存在!");
return;
}
...
#pragma endregion
#pragma region 以二进制形式读文件。存入varBlob
CFile file;
if (file.Open(fileName, CFile::modeRead|CFile::typeBinary) == FALSE)
{
return;
}
long fileLen = file.GetLength(); // 文件长度
// 存放文件二进制流的指针
byte *fileBuffer = new byte[fileLen + 1];
file.Read(fileBuffer, fileLen);
file.Close();
// 指定一个一维安全数组(safe array)的边界
SAFEARRAYBOUND rgsabound[1];
rgsabound[0].lLbound = 0;
rgsabound[0].cElements = fileLen;
// 安全数组
SAFEARRAY *safeArray;
safeArray = SafeArrayCreate(VT_UI1, 1, rgsabound);
for (long i = 0; i < fileLen; i++)
{
SafeArrayPutElement (safeArray, &i, fileBuffer++);
}
// 存入数据库中的BLOB的类型数据。设置为BYTE类型的数组
VARIANT varBLOB;
varBLOB.vt = VT_ARRAY | VT_UI1;
varBLOB.parray = safeArray;
#pragma endregion
#pragma region 插入记录
CString sql = L"select * from TABLE_NAME where 1 = 0";
_RecordsetPtr rs;
rs.CreateInstance(__uuidof(Recordset));
try
{
if (rs->Open(sql.GetBuffer(0), g_conn.GetInterfacePtr(),
adOpenDynamic, adLockOptimistic, adCmdText) == S_FALSE)
{
return;
}
GUID guid;
CoCreateGuid(&guid);
CString id;
id.Format(L"%08X%04X%04X%02X%02X%02X%02X%02X%02X%02X%02X",
guid.Data1, guid.Data2, guid.Data3,
guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
rs->AddNew();
rs->PutCollect("ID", _variant_t(id));
rs->PutCollect("...", ...);
rs->PutCollect("CAD_FILE", _variant_t(""));
rs->GetFields()->GetItem("FILE")->AppendChunk(varBLOB);
if (rs->Update() == S_OK)
{
...
}
else
{
...
}
}
catch(...)
{
...
}
rs = NULL;
#pragma endregion
CDialog::OnOK();
}
#pragma region 从数据库读取文件存到本地
CString tempFile; // 要存储到本地文件名。
_RecordsetPtr rs;
rs.CreateInstance(__uuidof(Recordset));
CString sql;
sql.Format(L"select FILE from tablename where id = '%s'", id);
try
{
if (rs->Open(sql.GetBuffer(0), g_conn.GetInterfacePtr(),
adOpenDynamic, adLockOptimistic, adCmdText) == S_FALSE)
{
return false;
}
if (rs->adoEOF)
{
return false;
}
long dataSize = rs->GetFields()->GetItem("FILE")->ActualSize;
if (dataSize < 0)
{
return false;
}
_variant_t varBlob = rs->GetFields()->GetItem("FILE")->GetChunk(dataSize);;
if(varBlob.vt == (VT_ARRAY | VT_UI1)) //判断数据类型是否正确
{
char *pBuf = NULL;
SafeArrayAccessData(varBlob.parray, (void **)&pBuf); //得到指向数据的指针
CFile cadFile;
tempFile = appPath + "\\temp.dwg";;
if (cadFile.Open(tempFile,
CFile::modeCreate|CFile::modeWrite|CFile::typeBinary) == FALSE)
{
return false;
}
cadFile.Write(pBuf, dataSize);
cadFile.Close();
SafeArrayUnaccessData (varBlob.parray);
}
}
catch (...)
{
return false;
}
#pragma endregion