c++連結SQL server ,用SQL語句打印表中的記錄,增加表中的記錄,刪除表的欄位
阿新 • • 發佈:2018-11-04
#import "c:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF", "adoEOF") rename("BOF", "adoBOF") // 唯一的應用程式物件 CWinApp theApp; using namespace std; class student//與資料庫中的欄位相同 { public: long snum; char sname[10]; long id; }; int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { student STU; //連線到MS SQL Server //初始化指標 CoInitialize(NULL); _ConnectionPtr pMyConnect = NULL; HRESULT hr = pMyConnect.CreateInstance(__uuidof(Connection)); if (FAILED(hr)) return 0; try { // Open方法連線字串必須四BSTR或者_bstr_t型別 pMyConnect->Open("Provider=SQLOLEDB;Server=100.63.96.252;Database=goo;uid=sa;pwd=1233;", "", "", NULL); cout << "connect success " << endl; } catch (_com_error &e) { string errorInfo = e.Description(); CoUninitialize(); return false; }//發生連結錯誤 _RecordsetPtr pRecordset; pRecordset.CreateInstance(__uuidof(Recordset)); CString strSql=“select * from student”; pRecordset->Open(strSql, pMyConnect.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText); //_variant_t vsid, vsnumber, vsname;//定義對應資料庫中表的欄位 ///////////////////////////////////////////////////////////////////////////////// ////////遍歷讀取資料並輸出 //while (!pRecordset->adoEOF)//遍歷並讀取記錄並輸出 //{ // //////////////////////////////////////////////////////////////////////// // //////獲取一行欄位 // vsid = pRecordset->GetCollect("id"); // vsnumber = pRecordset->GetCollect("number"); // vsname = pRecordset->GetCollect("name"); //// /////////////////////////////////////////////////////////////////////// //// ////按行列印 // if (vsid.vt != VT_NULL && vsnumber.vt != VT_NULL && vsname.vt != VT_NULL) // { // cout.setf(ios::left); // cout << setw(30) << (char*)(_bstr_t)vsid; // cout << setw(30) << (char*)(_bstr_t)vsnumber; // cout << setw(30) << (char*)(_bstr_t)vsname; // cout.unsetf(ios::left); // cout << endl; // } //// //////指標移到下一行 //pRecordset->MoveNext(); //} //////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////輸入資訊 cout << " 請輸入你要新增的資訊" << endl; cout << "學號"; cin >> STU.snum; cout << "編號"; cin >> STU.id; cout << "姓名"; cin >> STU.sname; pRecordset->MoveFirst();//移動到第一條記錄 pRecordset->AddNew();//新增新紀錄 pRecordset->PutCollect("name", (char*)(_bstr_t)(STU.sname)); pRecordset->PutCollect("number", (char*)(_bstr_t)(STU.snum)); pRecordset->PutCollect("id", (char*)(_bstr_t)(STU.id)); pRecordset->Update(); } catch (_com_error &e) { string errorInfo = e.Description(); CoUninitialize(); return false; } pMyConnect.Release(); pRecordset->Close(); system("pause"); }
以上只是部分程式碼,不能直接執行
檢視完整工程:https://download.csdn.net/download/qq_40155090/10578487