當前位置:編程學習大全網 - 源碼下載 - VC中寫SQl語句,查找數據,數據庫是sql2000

VC中寫SQl語句,查找數據,數據庫是sql2000

1. 在stdafx.h 添加下面代碼:

#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF")

2. 在C*App::InitInstance()中添加:

AfxOleInit();

3. 下面是壹個按鈕的相應事件, 數據庫連接字符串 和 查詢語句換成妳的就可以了:

void CTestDlg::OnButton1()

{

CString strDatasource = "my2005";

CString strDatabase = "myoa";

CString strUserName = "sa";

CString strUserPwd = "yourpwd";

CString strConn; // 連接數據庫字符串

CString strSql; // 查詢語句

CString strRet; // 查詢結果

LPTSTR lpszConn = NULL;

LPTSTR lpszSql = NULL;

_RecordsetPtr pRecordset;

_CommandPtr pCommand;

_ConnectionPtr pConnection;

strConn.Format(_T("Provider=SQLOLEDB.1;Data Source=%s;Initial Catalog=%s;User ID=%s; PWD=%s"), strDatasource, strDatabase, strUserName, strUserPwd);

strSql = _T("select pwd from UserInfo where loginName= 'test'");

try

{

HRESULT hr = pConnection.CreateInstance("ADODB.Connection");

lpszConn = new TCHAR[strConn.GetLength()+1];

_tcscpy(lpszConn, strConn);

pConnection->put_ConnectionTimeout(long(5));

if (SUCCEEDED(hr))

{

pConnection->Open(lpszConn, "", "", adModeUnknown); //adModeUnknown adConnectUnspecified

pRecordset.CreateInstance("ADODB.Recordset");

lpszSql = new TCHAR[strSql.GetLength()+1];

_tcscpy(lpszSql, strSql);

pRecordset = pConnection->Execute(lpszSql, NULL, adCmdText);

_variant_t vCount = pRecordset->GetCollect("pwd"); //取得第壹個字段的值放入vCount變量

strRet.Format((_bstr_t)vCount);

MessageBox(strRet); // 顯示查詢結果

}

}

catch(_com_error e)

{

CString strTemp;

strTemp.Format(_T("錯誤:\r\n%s"), e.ErrorMessage());

AfxMessageBox(strTemp);

return;

}

/*釋放資源*/

if (pRecordset->State)

{

pRecordset->Close();

pRecordset.Release();

pRecordset = NULL;

}

if ( pConnection->State)

{

pConnection->Close();

pConnection= NULL;

}

::CoUninitialize(); //釋放COM 資源。

if ( lpszConn != NULL)

delete lpszConn;

if ( lpszSql != NULL)

delete lpszSql;

}

註意: sql 語句 我壹般都是 查詢分析器裏 執行壹下,看是否有錯誤, 然後在代碼中構建 相應的字符串,根據字段的類型決定要不要 單引號。

  • 上一篇:話題辯論源代碼
  • 下一篇:iPhone如何設置懸浮按鍵?
  • copyright 2024編程學習大全網