C++連結SQL程式碼測試
{
CoInitialize(NULL);
_ConnectionPtr m_pConnection;
HRESULT hr=m_pConnection.CreateInstance(_uuidof(Connection));
if(FAILED(hr))
{
cout<<"_ConnectionPtr物件指標例項化失敗!!!"<<endl;
return ;
}
else {
try { /*127.0.0.1,1433*/
_bstr_t strConnect="Driver={sql server};server=(local);uid=sa;
m_pConnection->Open(strConnect,"sa","[email protected]",adModeUnknown);
}
catch(_com_error &e) {
cout<<e.Description()<<endl;
}
_RecordsetPtr m_pRecordset;
if(FAILED(m_pRecordset.CreateInstance( _uuidof( Recordset ))))
{
cout<<"記錄集物件指標例項化失敗!"<<endl;
return;
}
try {
m_pRecordset.CreateInstance("ADODB.Recordset");//從登錄檔
_variant_t ra ;
m_pConnection->Execute("CREATE TABLE student4(學號 INTEGER,姓名 TEXT,性別 TEXT,年齡 INTEGER,部門 TEXT)",&ra,adCmdText);
m_pConnection->Execute("INSERT INTO student4(學號,姓名,年齡,部門) VALUES (112105, '程紅秀',22,'市場部')",&ra,adCmdText);
m_pConnection->Execute("INSERT INTO student4(學號,姓名,年齡,部門) VALUES (112106, 'xx',25,'市場部')",&ra,adCmdText);
m_pConnection->Execute("INSERT INTO student4(學號,姓名,年齡,部門) VALUES (112107, '趙y',35,'市場部')",&ra,adCmdText);
char sql[100];
//sprintf_s(sql, "use 測試 update student1 set 姓名='全家性',部門='序號' where 年齡 =22", str1 );
//m_pConnection->Execute(sql,&ra,adCmdText);
m_pRecordset =m_pConnection->Execute("SELECT COUNT(*)FROM student5",&ra,adCmdText);
//取得第一個欄位值放入vCount變數
_variant_t vCount=m_pRecordset->GetCollect((_variant_t)(long)(0));
m_pRecordset->Close();
CString str;
str.Format(L"共有%d條記錄",vCount.iVal);
AfxMessageBox(str);
}
catch (_com_error &e)
{
cout << e.Description()<<endl;
}
try {
m_pRecordset->MoveFirst();
while(!m_pRecordset->adoEOF)
{
string insertTime=(char*)(_bstr_t)(m_pRecordset->Fields->GetItem(_variant_t("InsertTime"))->Value);
cout<<insertTime<<endl;
m_pRecordset->MoveNext();
}
}
catch (_com_error &e)
{
cout << e.Description()<<endl;
}
}
//system("pause");
CDialogEx::OnOK();
}