VC++中ADO方式運算元據庫之有關“datetime”欄位的操作

unshaken2011發表於2012-10-13

直接上程式碼:
void CADOConDlg::OnButton1() 
{
	// TODO: Add your control notification handler code here
	HRESULT hr;
	CString strSql;
	_ConnectionPtr m_pConnection;
	_RecordsetPtr m_pRecordset;
	try
	{
		//create the SQL service object 
		hr = m_pConnection.CreateInstance(__uuidof(Connection));
		ASSERT( SUCCEEDED(hr) );
		strSql.Format("%s","Provider=SQLOLEDB;server=xxx;database=xxx;UID=xxx;PWD=xxx");
		m_pConnection->ConnectionString = (_bstr_t)strSql;
		hr = m_pConnection->Open("","","",adConnectUnspecified);
		ASSERT( SUCCEEDED(hr) );
		//create the record set object for write
		hr = m_pRecordset.CreateInstance(__uuidof(Recordset));
		ASSERT( SUCCEEDED(hr) );

		CString strCurrentTime;
		strSql.Format(_T("select * from 。。。='。。' "));
		m_pRecordset->raw_Close();
		m_pRecordset->CursorLocation = adUseClient;
		hr = m_pRecordset->Open((_variant_t)strSql, m_pConnection.GetInterfacePtr(), adOpenKeyset, adLockOptimistic, adCmdText);
		
		SYSTEMTIME sys;  
		GetLocalTime( &sys );  
		strCurrentTime.Format(_T("%d-%d-%d %d:%d:%d"),sys.wYear,sys.wMonth,sys.wDay,sys.wHour,sys.wMinute,sys.wSecond);
		_variant_t varTime = (LPCTSTR)strCurrentTime;

		m_pRecordset->Update("datetime",(_variant_t)(COleDateTime)varTime);
//		m_pRecordset->Update("datetime",(_variant_t)(COleDateTime)sys);
		//COleDateTime只精確到秒級
		//查下MSDN就知道,其實(COleDateTime)強轉的型別可以很多
		AfxMessageBox("successful");

		CString strTimeGet;
		_variant_t varTimeGet;
		COleDateTime oleTimeGet;  
		SYSTEMTIME sysTimeGet;
		varTimeGet=m_pRecordset->GetCollect("datetime");
		if (varTimeGet.vt!=VT_NULL)
		{
			//strTimeGet=varTimeGet.bstrVal;//此路不通
			oleTimeGet=(COleDateTime)varTimeGet;
			VariantTimeToSystemTime(oleTimeGet,&sysTimeGet);
			strTimeGet.Format(_T("%d-%d-%d %d:%d:%d"),sysTimeGet.wYear,sysTimeGet.wMonth,sysTimeGet.wDay,
				sysTimeGet.wHour,sysTimeGet.wMinute,sysTimeGet.wSecond);
			AfxMessageBox(strTimeGet);
		}
	}
	catch (_com_error e)
	{
		//CWnd::MessageBox(e.ErrorMessage(), "error DB select read!", NULL);
		AfxMessageBox(e.Description());
	}
}

感謝:http://blog.csdn.net/leeedreadful/article/details/6804366給瞭解決問題的思路。。。


相關文章