用的是单文档类型,菜单上有“销售报告->按产品”一项,其对应函数:OnSaleProduct(),将销售报告按产品进行统计,并将结果显示在视图里:
CListCtrl& ctrlList=(CListCtrl&) GetListCtrl();
ctrlList.DeleteAllItems();
while(ctrlList.DeleteColumn(0));
UpdateWindow();
CString strSQL;
strSQL=_T("SELECT *FROM SalesByProduct;");
if(!ShowInformation(strSQL)) AfxMessageBox("数据获取失败!");
m_uStatus=TABLE_PRODUCTS;
可是我照书上的做,编译时却出现问题:
‘GetListCtrl' : undeclared identifier
这个函数到底怎么用,或许要加什么头文件,
请前辈们指教。谢谢
另外
'm_uStatus' : undeclared identifier
'TABLE_PRODUCTS' : undeclared identifier
请问:'m_uStatus' 是哪个类带的数据成员,我建表时根本就没有用'TABLE_PRODUCTS' ,
'TABLE_PRODUCTS' 是什么东西?
6 个解决方案
#1
如果没有随书的源代码,那仔细检查你的书,应该还有一些其它的内容,你没有看全,从书里找答案。
如果随书带有源代码,看看光盘上是否有这个例子,打开相关的例子,应该就可以找到你提出的这些字
如果随书带有源代码,看看光盘上是否有这个例子,打开相关的例子,应该就可以找到你提出的这些字
#2
哈哈,,,搞错了吧.真是将结果显示在视图里吗>
CListCtrl& ctrlList=(CListCtrl&) GetListCtrl();是对话框类的LISTCTRL控件,连数据库用到它一般是将查询结果导入LISTCTRL中的,导入之前还要先绑定的,VC连数据库本来就有点麻烦.....建意你建军一个DIALG工程试下 :
我有一个ADO的类ODBC一样可以用的:
CListCtrl& ctrlList=(CListCtrl&) GetListCtrl();是对话框类的LISTCTRL控件,连数据库用到它一般是将查询结果导入LISTCTRL中的,导入之前还要先绑定的,VC连数据库本来就有点麻烦.....建意你建军一个DIALG工程试下 :
我有一个ADO的类ODBC一样可以用的:
#3
// ADOConn.h: interface for the CADOConn class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_ADOCONN1_H__E411A6A3_90BA_4C07_8BC5_5F48FFF4DB07__INCLUDED_)
#define AFX_ADOCONN1_H__E411A6A3_90BA_4C07_8BC5_5F48FFF4DB07__INCLUDED_
//#include <ole2.h>
//#include <stdio.h>
//#include <conio.h>
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "sqlext.h"
//#import "d:\Program Files\Common Files\System\ado\msado15.dll"no_namespace rename("EOF","adoEOF")rename("BOF","adoBOF")
class CADOConn
{
public:
CADOConn();
virtual ~CADOConn();
public:
//ADODB::_ConnectionPtr m_pConnect
_ConnectionPtr m_pConnection;
_RecordsetPtr m_pRecordset;
public:
//初始化——连接数据库
static void OnInitDBConnect();
//执行查询
_RecordsetPtr& GetRecordSet(_bstr_t bstrSQL);
//Insetr Update _variant_t
BOOL ExecuteSQL(_bstr_t bstrSQL);
void ExitConnect();
//获得表长
int GetRecordCount(CString strTable, int &nCount, CString strCondition = _T(""));
//表名,待查字段名数组,待查字段个数,查询结果数组,查询条件“ where。。。”
int SelectRecordSet(CString strTable, CString *strFields,
int nFieldnum, CString **strResult, CString strCondition = _T(""));
int InsertRecord(CString strTable, int nCount, CString *strFields, CString *strValue,
CString strkeyfield = _T(""), CString strkey = _T(""));
};
#endif // !defined(AFX_ADOCONN1_H__E411A6A3_90BA_4C07_8BC5_5F48FFF4DB07__INCLUDED_)
.CPP文件如下:
// ADOConn.cpp: implementation of the CADOConn class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ADOConn.h"
//#include "ExamTest.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
//extern CLABMANAGEApp theApp;
CADOConn::CADOConn()
{
}
CADOConn::~CADOConn()
{
}
void CADOConn::OnInitDBConnect()
{
AfxMessageBox("start to connect!");
CString strUser;
CString strServer;
CString strPwd;
CString strConnection;
/*strUser = theApp.m_UserName;
strPwd = theApp.m_Password;
strServer = theApp.m_ServerName;*/
strServer = "QEQ";
strConnection = "Provider=SQLOLEDB;Server=";
strConnection+= strServer + ";Database=sturecord";
/*strConnection+= strUser + ";pwd=";
strConnection+= strPwd + ";";*/
::CoInitialize(NULL);
try
{
m_pConnection.CreateInstance(__uuidof(Connection));//******************
_bstr_t strConnect = (_bstr_t)strConnection;
m_pConnection->Open(strConnect,"","",adModeUnknown);//****************
}
catch(_com_error e)
{
AfxMessageBox(e.Description()+"系统退出!");
exit(0);
}
}
_RecordsetPtr& CADOConn::GetRecordSet(_bstr_t bstrSQL)
{
try
{
if (m_pConnection == NULL)
{
OnInitDBConnect();
}
m_pRecordset.CreateInstance(_uuidof(Recordset));
m_pRecordset->Open(bstrSQL, (_variant_t)m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
}
catch (_com_error e)
{
AfxMessageBox(e.Description()+"系统退出!");
exit(0);
}
return m_pRecordset;
_variant_t var;
}
BOOL CADOConn::ExecuteSQL(_bstr_t bstrSQL)//************************
{
try
{
if (m_pConnection ==NULL)
{
AfxMessageBox("自动连接!");
OnInitDBConnect();
}
m_pConnection->Execute(bstrSQL,NULL,adCmdText);
}
catch (_com_error e)
{
AfxMessageBox(e.Description()+"系统退出!");
exit(0);
return false;
}
return true;
}
void CADOConn::ExitConnect()
{
if (m_pRecordset != NULL)
{
m_pRecordset->Close();
m_pConnection->Close();
::CoUninitialize();
}
}
////注意m_Storedata=VT_NULL的情况,要做处理, 暂不处理
int CADOConn::SelectRecordSet(CString strTable, CString *strFields, int nFieldnum,
CString **strResult, CString strCondition)
{
CString m_sql;
int nRecordCnd = 0;
_variant_t varTemp;
_RecordsetPtr m_pRecord = NULL;
m_sql = "select * from " + strTable + " " + strCondition;
try
{
m_pRecord = GetRecordSet((_bstr_t)m_sql);
if (m_pRecord!=NULL)
{
if (!m_pRecord->adoBOF)
{
m_pRecord->MoveFirst();
}
while(!m_pRecord->adoEOF)
{
for (int i=0; i<nFieldnum; i++)
{
varTemp = m_pRecord->GetCollect((_bstr_t)strFields[i]);
strResult[nRecordCnd][i] = (LPCSTR)_bstr_t(varTemp);
}
m_pRecord->MoveNext();
nRecordCnd++;
}
}
/* else
{
return 2;
}*/
}
catch (...)
{
AfxMessageBox("数据库错误");
return -1;
}
return 1;
}
int CADOConn::GetRecordCount(CString strTable, int &nCount, CString strCondition)
{
_RecordsetPtr m_pRecord = NULL;
int nCounter = 0;
CString m_sql;
m_sql = "select * from " + strTable + strCondition;
try
{
m_pRecord = GetRecordSet((_bstr_t)m_sql);
if (m_pRecord!=NULL)
{
if (!m_pRecord->adoBOF)
{
m_pRecord->MoveFirst();
}
while(!m_pRecord->adoEOF)
{
m_pRecord->MoveNext();
nCounter++;
}
}
nCount = nCounter;
}
catch (...)
{
AfxMessageBox("数据库错误");
return -1;
}
return 1;
}
//return -1:主键冲突/////////////////注意m_Storedata=VT_NULL的情况,要做处理
int CADOConn::InsertRecord(CString strTable, int nCount, CString *strFields,
CString *strValue,CString strKeyfield, CString strKey)
{
CString m_sql;
_RecordsetPtr m_pRecord;
_variant_t m_Storedata;
try
{
if (strKeyfield != "")
{
m_sql = "select * from " + strTable;
m_pRecord = GetRecordSet((_bstr_t)m_sql);
if (m_pRecord!=NULL)
{
if (!m_pRecord->adoBOF)
{
m_pRecord->MoveFirst();
}
while (!m_pRecord->adoEOF)
{
m_Storedata = m_pRecord->GetCollect((_bstr_t)strKeyfield);
if ((LPCSTR)_bstr_t(m_Storedata)==strKey)
{
return 0;
}
m_pRecord->MoveNext();
}
}
}
m_sql = "insert into " + strTable + " (";
for (int i=0; i<nCount-1; i++)
{
m_sql += strFields[i] + ",";
}
m_sql += strFields[nCount-1] + ") ";
m_sql += "values (";
for (i=0; i<nCount-1; i++)
{
m_sql += strValue[i] + ",";
}
m_sql += strValue[nCount-1] + ") ";
ExecuteSQL((_bstr_t)m_sql);
}
catch (...)
{
AfxMessageBox("数据库错误");
return -1;
}
return 1;
}
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_ADOCONN1_H__E411A6A3_90BA_4C07_8BC5_5F48FFF4DB07__INCLUDED_)
#define AFX_ADOCONN1_H__E411A6A3_90BA_4C07_8BC5_5F48FFF4DB07__INCLUDED_
//#include <ole2.h>
//#include <stdio.h>
//#include <conio.h>
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "sqlext.h"
//#import "d:\Program Files\Common Files\System\ado\msado15.dll"no_namespace rename("EOF","adoEOF")rename("BOF","adoBOF")
class CADOConn
{
public:
CADOConn();
virtual ~CADOConn();
public:
//ADODB::_ConnectionPtr m_pConnect
_ConnectionPtr m_pConnection;
_RecordsetPtr m_pRecordset;
public:
//初始化——连接数据库
static void OnInitDBConnect();
//执行查询
_RecordsetPtr& GetRecordSet(_bstr_t bstrSQL);
//Insetr Update _variant_t
BOOL ExecuteSQL(_bstr_t bstrSQL);
void ExitConnect();
//获得表长
int GetRecordCount(CString strTable, int &nCount, CString strCondition = _T(""));
//表名,待查字段名数组,待查字段个数,查询结果数组,查询条件“ where。。。”
int SelectRecordSet(CString strTable, CString *strFields,
int nFieldnum, CString **strResult, CString strCondition = _T(""));
int InsertRecord(CString strTable, int nCount, CString *strFields, CString *strValue,
CString strkeyfield = _T(""), CString strkey = _T(""));
};
#endif // !defined(AFX_ADOCONN1_H__E411A6A3_90BA_4C07_8BC5_5F48FFF4DB07__INCLUDED_)
.CPP文件如下:
// ADOConn.cpp: implementation of the CADOConn class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ADOConn.h"
//#include "ExamTest.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
//extern CLABMANAGEApp theApp;
CADOConn::CADOConn()
{
}
CADOConn::~CADOConn()
{
}
void CADOConn::OnInitDBConnect()
{
AfxMessageBox("start to connect!");
CString strUser;
CString strServer;
CString strPwd;
CString strConnection;
/*strUser = theApp.m_UserName;
strPwd = theApp.m_Password;
strServer = theApp.m_ServerName;*/
strServer = "QEQ";
strConnection = "Provider=SQLOLEDB;Server=";
strConnection+= strServer + ";Database=sturecord";
/*strConnection+= strUser + ";pwd=";
strConnection+= strPwd + ";";*/
::CoInitialize(NULL);
try
{
m_pConnection.CreateInstance(__uuidof(Connection));//******************
_bstr_t strConnect = (_bstr_t)strConnection;
m_pConnection->Open(strConnect,"","",adModeUnknown);//****************
}
catch(_com_error e)
{
AfxMessageBox(e.Description()+"系统退出!");
exit(0);
}
}
_RecordsetPtr& CADOConn::GetRecordSet(_bstr_t bstrSQL)
{
try
{
if (m_pConnection == NULL)
{
OnInitDBConnect();
}
m_pRecordset.CreateInstance(_uuidof(Recordset));
m_pRecordset->Open(bstrSQL, (_variant_t)m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
}
catch (_com_error e)
{
AfxMessageBox(e.Description()+"系统退出!");
exit(0);
}
return m_pRecordset;
_variant_t var;
}
BOOL CADOConn::ExecuteSQL(_bstr_t bstrSQL)//************************
{
try
{
if (m_pConnection ==NULL)
{
AfxMessageBox("自动连接!");
OnInitDBConnect();
}
m_pConnection->Execute(bstrSQL,NULL,adCmdText);
}
catch (_com_error e)
{
AfxMessageBox(e.Description()+"系统退出!");
exit(0);
return false;
}
return true;
}
void CADOConn::ExitConnect()
{
if (m_pRecordset != NULL)
{
m_pRecordset->Close();
m_pConnection->Close();
::CoUninitialize();
}
}
////注意m_Storedata=VT_NULL的情况,要做处理, 暂不处理
int CADOConn::SelectRecordSet(CString strTable, CString *strFields, int nFieldnum,
CString **strResult, CString strCondition)
{
CString m_sql;
int nRecordCnd = 0;
_variant_t varTemp;
_RecordsetPtr m_pRecord = NULL;
m_sql = "select * from " + strTable + " " + strCondition;
try
{
m_pRecord = GetRecordSet((_bstr_t)m_sql);
if (m_pRecord!=NULL)
{
if (!m_pRecord->adoBOF)
{
m_pRecord->MoveFirst();
}
while(!m_pRecord->adoEOF)
{
for (int i=0; i<nFieldnum; i++)
{
varTemp = m_pRecord->GetCollect((_bstr_t)strFields[i]);
strResult[nRecordCnd][i] = (LPCSTR)_bstr_t(varTemp);
}
m_pRecord->MoveNext();
nRecordCnd++;
}
}
/* else
{
return 2;
}*/
}
catch (...)
{
AfxMessageBox("数据库错误");
return -1;
}
return 1;
}
int CADOConn::GetRecordCount(CString strTable, int &nCount, CString strCondition)
{
_RecordsetPtr m_pRecord = NULL;
int nCounter = 0;
CString m_sql;
m_sql = "select * from " + strTable + strCondition;
try
{
m_pRecord = GetRecordSet((_bstr_t)m_sql);
if (m_pRecord!=NULL)
{
if (!m_pRecord->adoBOF)
{
m_pRecord->MoveFirst();
}
while(!m_pRecord->adoEOF)
{
m_pRecord->MoveNext();
nCounter++;
}
}
nCount = nCounter;
}
catch (...)
{
AfxMessageBox("数据库错误");
return -1;
}
return 1;
}
//return -1:主键冲突/////////////////注意m_Storedata=VT_NULL的情况,要做处理
int CADOConn::InsertRecord(CString strTable, int nCount, CString *strFields,
CString *strValue,CString strKeyfield, CString strKey)
{
CString m_sql;
_RecordsetPtr m_pRecord;
_variant_t m_Storedata;
try
{
if (strKeyfield != "")
{
m_sql = "select * from " + strTable;
m_pRecord = GetRecordSet((_bstr_t)m_sql);
if (m_pRecord!=NULL)
{
if (!m_pRecord->adoBOF)
{
m_pRecord->MoveFirst();
}
while (!m_pRecord->adoEOF)
{
m_Storedata = m_pRecord->GetCollect((_bstr_t)strKeyfield);
if ((LPCSTR)_bstr_t(m_Storedata)==strKey)
{
return 0;
}
m_pRecord->MoveNext();
}
}
}
m_sql = "insert into " + strTable + " (";
for (int i=0; i<nCount-1; i++)
{
m_sql += strFields[i] + ",";
}
m_sql += strFields[nCount-1] + ") ";
m_sql += "values (";
for (i=0; i<nCount-1; i++)
{
m_sql += strValue[i] + ",";
}
m_sql += strValue[nCount-1] + ") ";
ExecuteSQL((_bstr_t)m_sql);
}
catch (...)
{
AfxMessageBox("数据库错误");
return -1;
}
return 1;
}
#4
ADO不会用,我是个用MFC的新手,有没有更简单的办法啊?
#5
如果你对MFC不熟悉,可以先用Console来写程序,学习ADO。
下面是一个Console的程序,是演示ADO的MoveFirst等功能的使用。
这是MSDN的例子,在MSDN里还有很多其它的例子,如果你买两三本ADO的书,再结合这些例子,会很快上手ADO的。另外你还需要一个数据库软件配合,即然你是新手,可以使用SQL Server 2000。这样会方便很多。祝你好运
// BeginMoveFirstCpp
#include <ole2.h>
#include <stdio.h>
#import "c:\Program Files\Common Files\System\ADO\msado15.dll" \
no_namespace rename("EOF", "EndOfFile")
// Function declarations
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void MoveFirstX();
void MoveAny(int intChoice, _RecordsetPtr pRstTemp);
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
/////////////////////////////////
// Main Function //
/////////////////////////////////
void main()
{
if(FAILED(::CoInitialize(NULL)))
return;
MoveFirstX();
::CoUninitialize();
}
//////////////////////////////////////
// MoveFirstX Function //
//////////////////////////////////////
void MoveFirstX()
{
HRESULT hr = S_OK;
_RecordsetPtr pRstAuthors = NULL;
_bstr_t strCnn("Provider='sqloledb';Data Source='MySqlServer';"
"Initial Catalog='pubs';Integrated Security='SSPI';");
_bstr_t strMessage("UPDATE Titles SET Type = "
"'psychology' WHERE Type = 'self_help'");
int intCommand = 0;
// Temporary string variable for type conversion for printing.
_bstr_t bstrFName;
_bstr_t bstrLName;
try
{
// Open recordset from Authors table.
TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));
pRstAuthors->CursorType = adOpenStatic;
// Use client cursor to enable AbsolutePosition property.
pRstAuthors->CursorLocation = adUseClient;
pRstAuthors->Open("Authors", strCnn, adOpenStatic,
adLockBatchOptimistic, adCmdTable);
// Show current record information and get user's method choice.
while (true) // Continuous loop.
{
// Convert variant string to convertable string type.
bstrFName = pRstAuthors->Fields->Item["au_fName"]->Value;
bstrLName = pRstAuthors->Fields->Item["au_lName"]->Value;
printf("Name: %s %s\n Record %d of %d\n\n",
(LPCSTR) bstrFName,
(LPCSTR) bstrLName,
pRstAuthors->AbsolutePosition,
pRstAuthors->RecordCount);
printf("[1 - MoveFirst, 2 - MoveLast, \n");
printf(" 3 - MoveNext, 4 - MovePrevious, 5 - Quit]\n");
scanf("%d", &intCommand);
if ((intCommand < 1) || (intCommand > 4))
break; // Out of range entry exits program loop.
// Call method based on user's input.
MoveAny(intCommand, pRstAuthors);
}
}
catch (_com_error &e)
{
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstAuthors->GetActiveConnection();
// GetActiveConnection returns connect string if connection
// is not open, else returns Connection object.
switch(vtConnect.vt)
{
case VT_BSTR:
PrintComError(e);
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
}
// Clean up objects before exit.
if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
}
/////////////////////////////////
// MoveAny Function //
/////////////////////////////////
void MoveAny(int intChoice, _RecordsetPtr pRstTemp)
{
// Use specified method, trapping for BOF and EOF
try
{
switch(intChoice)
{
case 1:
pRstTemp->MoveFirst();
break;
case 2:
pRstTemp->MoveLast();
break;
case 3:
pRstTemp->MoveNext();
if (pRstTemp->EndOfFile)
{
printf("\nAlready at end of recordset!\n");
pRstTemp->MoveLast();
} //End If
break;
case 4:
pRstTemp->MovePrevious();
if (pRstTemp->BOF)
{
printf("\nAlready at beginning of recordset!\n");
pRstTemp->MoveFirst();
}
break;
default:
;
}
}
catch(_com_error &e)
{
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstTemp->GetActiveConnection();
// GetActiveConnection returns connect string if connection
// is not open, else returns Connection object.
switch(vtConnect.vt)
{
case VT_BSTR:
PrintComError(e);
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
}
}
////////////////////////////////////////////
// PrintProviderError Function //
////////////////////////////////////////////
void PrintProviderError(_ConnectionPtr pConnection)
{
// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;
if( (pConnection->Errors->Count) > 0)
{
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount - 1.
for(long i = 0; i < nCount; i++)
{
pErr = pConnection->Errors->GetItem(i);
printf("\t Error number: %x\t%s", pErr->Number,
pErr->Description);
}
}
}
//////////////////////////////////////
// PrintComError Function //
//////////////////////////////////////
void PrintComError(_com_error &e)
{
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
// Print Com errors.
printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}
// EndMoveFirstCpp
下面是一个Console的程序,是演示ADO的MoveFirst等功能的使用。
这是MSDN的例子,在MSDN里还有很多其它的例子,如果你买两三本ADO的书,再结合这些例子,会很快上手ADO的。另外你还需要一个数据库软件配合,即然你是新手,可以使用SQL Server 2000。这样会方便很多。祝你好运
// BeginMoveFirstCpp
#include <ole2.h>
#include <stdio.h>
#import "c:\Program Files\Common Files\System\ADO\msado15.dll" \
no_namespace rename("EOF", "EndOfFile")
// Function declarations
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void MoveFirstX();
void MoveAny(int intChoice, _RecordsetPtr pRstTemp);
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
/////////////////////////////////
// Main Function //
/////////////////////////////////
void main()
{
if(FAILED(::CoInitialize(NULL)))
return;
MoveFirstX();
::CoUninitialize();
}
//////////////////////////////////////
// MoveFirstX Function //
//////////////////////////////////////
void MoveFirstX()
{
HRESULT hr = S_OK;
_RecordsetPtr pRstAuthors = NULL;
_bstr_t strCnn("Provider='sqloledb';Data Source='MySqlServer';"
"Initial Catalog='pubs';Integrated Security='SSPI';");
_bstr_t strMessage("UPDATE Titles SET Type = "
"'psychology' WHERE Type = 'self_help'");
int intCommand = 0;
// Temporary string variable for type conversion for printing.
_bstr_t bstrFName;
_bstr_t bstrLName;
try
{
// Open recordset from Authors table.
TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));
pRstAuthors->CursorType = adOpenStatic;
// Use client cursor to enable AbsolutePosition property.
pRstAuthors->CursorLocation = adUseClient;
pRstAuthors->Open("Authors", strCnn, adOpenStatic,
adLockBatchOptimistic, adCmdTable);
// Show current record information and get user's method choice.
while (true) // Continuous loop.
{
// Convert variant string to convertable string type.
bstrFName = pRstAuthors->Fields->Item["au_fName"]->Value;
bstrLName = pRstAuthors->Fields->Item["au_lName"]->Value;
printf("Name: %s %s\n Record %d of %d\n\n",
(LPCSTR) bstrFName,
(LPCSTR) bstrLName,
pRstAuthors->AbsolutePosition,
pRstAuthors->RecordCount);
printf("[1 - MoveFirst, 2 - MoveLast, \n");
printf(" 3 - MoveNext, 4 - MovePrevious, 5 - Quit]\n");
scanf("%d", &intCommand);
if ((intCommand < 1) || (intCommand > 4))
break; // Out of range entry exits program loop.
// Call method based on user's input.
MoveAny(intCommand, pRstAuthors);
}
}
catch (_com_error &e)
{
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstAuthors->GetActiveConnection();
// GetActiveConnection returns connect string if connection
// is not open, else returns Connection object.
switch(vtConnect.vt)
{
case VT_BSTR:
PrintComError(e);
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
}
// Clean up objects before exit.
if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
}
/////////////////////////////////
// MoveAny Function //
/////////////////////////////////
void MoveAny(int intChoice, _RecordsetPtr pRstTemp)
{
// Use specified method, trapping for BOF and EOF
try
{
switch(intChoice)
{
case 1:
pRstTemp->MoveFirst();
break;
case 2:
pRstTemp->MoveLast();
break;
case 3:
pRstTemp->MoveNext();
if (pRstTemp->EndOfFile)
{
printf("\nAlready at end of recordset!\n");
pRstTemp->MoveLast();
} //End If
break;
case 4:
pRstTemp->MovePrevious();
if (pRstTemp->BOF)
{
printf("\nAlready at beginning of recordset!\n");
pRstTemp->MoveFirst();
}
break;
default:
;
}
}
catch(_com_error &e)
{
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstTemp->GetActiveConnection();
// GetActiveConnection returns connect string if connection
// is not open, else returns Connection object.
switch(vtConnect.vt)
{
case VT_BSTR:
PrintComError(e);
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
}
}
////////////////////////////////////////////
// PrintProviderError Function //
////////////////////////////////////////////
void PrintProviderError(_ConnectionPtr pConnection)
{
// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;
if( (pConnection->Errors->Count) > 0)
{
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount - 1.
for(long i = 0; i < nCount; i++)
{
pErr = pConnection->Errors->GetItem(i);
printf("\t Error number: %x\t%s", pErr->Number,
pErr->Description);
}
}
}
//////////////////////////////////////
// PrintComError Function //
//////////////////////////////////////
void PrintComError(_com_error &e)
{
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
// Print Com errors.
printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}
// EndMoveFirstCpp
#6
上面给你的两段代码,是我使用的完整代码:
你在你的工程中增加一个新类把,上面的.H文件加到你的头文件
把.CPP文件加入到你的CPP文件中,
然后那个类中要用到数据库查询,就把这个新类INCLUDE进去,然后调用不是很难的....给你一段调用的实例,供参考:
//向表PUB_XSQDB写入以上信息
CADOConn myInsert;
CString mySQL;
CString insertfilds;
insertfilds = "insert into PUB_XSQDB(DLH_PK,BM,YHM,QDSJ,QDRQ,SYPTH_PK,SYSMC) VALUES(";
CString strfgf1;
strfgf1 = "'";
CString strfgf2;
strfgf2 = "',";
CString sysmc;
sysmc = "'电工实验室'";
CString ykh;
ykh = ")";
mySQL = insertfilds +strfgf1+studentxh+strfgf2+ strfgf1+strbj+ strfgf2 + strfgf1 + studentname + strfgf2 + strfgf1 +s_currenttime+strfgf2+strfgf1+s_currentdate+strfgf2 + strfgf1+labinfo[i].labnumber +strfgf2+ sysmc +ykh;
消息myInsert.ExecuteSQL((_bstr_t)mySQL);
mySQL就是一个SQL插入语句,再不会用的话帮为不了你了....多找人问下更直接论坛里很难说清楚!
你在你的工程中增加一个新类把,上面的.H文件加到你的头文件
把.CPP文件加入到你的CPP文件中,
然后那个类中要用到数据库查询,就把这个新类INCLUDE进去,然后调用不是很难的....给你一段调用的实例,供参考:
//向表PUB_XSQDB写入以上信息
CADOConn myInsert;
CString mySQL;
CString insertfilds;
insertfilds = "insert into PUB_XSQDB(DLH_PK,BM,YHM,QDSJ,QDRQ,SYPTH_PK,SYSMC) VALUES(";
CString strfgf1;
strfgf1 = "'";
CString strfgf2;
strfgf2 = "',";
CString sysmc;
sysmc = "'电工实验室'";
CString ykh;
ykh = ")";
mySQL = insertfilds +strfgf1+studentxh+strfgf2+ strfgf1+strbj+ strfgf2 + strfgf1 + studentname + strfgf2 + strfgf1 +s_currenttime+strfgf2+strfgf1+s_currentdate+strfgf2 + strfgf1+labinfo[i].labnumber +strfgf2+ sysmc +ykh;
消息myInsert.ExecuteSQL((_bstr_t)mySQL);
mySQL就是一个SQL插入语句,再不会用的话帮为不了你了....多找人问下更直接论坛里很难说清楚!
#1
如果没有随书的源代码,那仔细检查你的书,应该还有一些其它的内容,你没有看全,从书里找答案。
如果随书带有源代码,看看光盘上是否有这个例子,打开相关的例子,应该就可以找到你提出的这些字
如果随书带有源代码,看看光盘上是否有这个例子,打开相关的例子,应该就可以找到你提出的这些字
#2
哈哈,,,搞错了吧.真是将结果显示在视图里吗>
CListCtrl& ctrlList=(CListCtrl&) GetListCtrl();是对话框类的LISTCTRL控件,连数据库用到它一般是将查询结果导入LISTCTRL中的,导入之前还要先绑定的,VC连数据库本来就有点麻烦.....建意你建军一个DIALG工程试下 :
我有一个ADO的类ODBC一样可以用的:
CListCtrl& ctrlList=(CListCtrl&) GetListCtrl();是对话框类的LISTCTRL控件,连数据库用到它一般是将查询结果导入LISTCTRL中的,导入之前还要先绑定的,VC连数据库本来就有点麻烦.....建意你建军一个DIALG工程试下 :
我有一个ADO的类ODBC一样可以用的:
#3
// ADOConn.h: interface for the CADOConn class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_ADOCONN1_H__E411A6A3_90BA_4C07_8BC5_5F48FFF4DB07__INCLUDED_)
#define AFX_ADOCONN1_H__E411A6A3_90BA_4C07_8BC5_5F48FFF4DB07__INCLUDED_
//#include <ole2.h>
//#include <stdio.h>
//#include <conio.h>
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "sqlext.h"
//#import "d:\Program Files\Common Files\System\ado\msado15.dll"no_namespace rename("EOF","adoEOF")rename("BOF","adoBOF")
class CADOConn
{
public:
CADOConn();
virtual ~CADOConn();
public:
//ADODB::_ConnectionPtr m_pConnect
_ConnectionPtr m_pConnection;
_RecordsetPtr m_pRecordset;
public:
//初始化——连接数据库
static void OnInitDBConnect();
//执行查询
_RecordsetPtr& GetRecordSet(_bstr_t bstrSQL);
//Insetr Update _variant_t
BOOL ExecuteSQL(_bstr_t bstrSQL);
void ExitConnect();
//获得表长
int GetRecordCount(CString strTable, int &nCount, CString strCondition = _T(""));
//表名,待查字段名数组,待查字段个数,查询结果数组,查询条件“ where。。。”
int SelectRecordSet(CString strTable, CString *strFields,
int nFieldnum, CString **strResult, CString strCondition = _T(""));
int InsertRecord(CString strTable, int nCount, CString *strFields, CString *strValue,
CString strkeyfield = _T(""), CString strkey = _T(""));
};
#endif // !defined(AFX_ADOCONN1_H__E411A6A3_90BA_4C07_8BC5_5F48FFF4DB07__INCLUDED_)
.CPP文件如下:
// ADOConn.cpp: implementation of the CADOConn class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ADOConn.h"
//#include "ExamTest.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
//extern CLABMANAGEApp theApp;
CADOConn::CADOConn()
{
}
CADOConn::~CADOConn()
{
}
void CADOConn::OnInitDBConnect()
{
AfxMessageBox("start to connect!");
CString strUser;
CString strServer;
CString strPwd;
CString strConnection;
/*strUser = theApp.m_UserName;
strPwd = theApp.m_Password;
strServer = theApp.m_ServerName;*/
strServer = "QEQ";
strConnection = "Provider=SQLOLEDB;Server=";
strConnection+= strServer + ";Database=sturecord";
/*strConnection+= strUser + ";pwd=";
strConnection+= strPwd + ";";*/
::CoInitialize(NULL);
try
{
m_pConnection.CreateInstance(__uuidof(Connection));//******************
_bstr_t strConnect = (_bstr_t)strConnection;
m_pConnection->Open(strConnect,"","",adModeUnknown);//****************
}
catch(_com_error e)
{
AfxMessageBox(e.Description()+"系统退出!");
exit(0);
}
}
_RecordsetPtr& CADOConn::GetRecordSet(_bstr_t bstrSQL)
{
try
{
if (m_pConnection == NULL)
{
OnInitDBConnect();
}
m_pRecordset.CreateInstance(_uuidof(Recordset));
m_pRecordset->Open(bstrSQL, (_variant_t)m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
}
catch (_com_error e)
{
AfxMessageBox(e.Description()+"系统退出!");
exit(0);
}
return m_pRecordset;
_variant_t var;
}
BOOL CADOConn::ExecuteSQL(_bstr_t bstrSQL)//************************
{
try
{
if (m_pConnection ==NULL)
{
AfxMessageBox("自动连接!");
OnInitDBConnect();
}
m_pConnection->Execute(bstrSQL,NULL,adCmdText);
}
catch (_com_error e)
{
AfxMessageBox(e.Description()+"系统退出!");
exit(0);
return false;
}
return true;
}
void CADOConn::ExitConnect()
{
if (m_pRecordset != NULL)
{
m_pRecordset->Close();
m_pConnection->Close();
::CoUninitialize();
}
}
////注意m_Storedata=VT_NULL的情况,要做处理, 暂不处理
int CADOConn::SelectRecordSet(CString strTable, CString *strFields, int nFieldnum,
CString **strResult, CString strCondition)
{
CString m_sql;
int nRecordCnd = 0;
_variant_t varTemp;
_RecordsetPtr m_pRecord = NULL;
m_sql = "select * from " + strTable + " " + strCondition;
try
{
m_pRecord = GetRecordSet((_bstr_t)m_sql);
if (m_pRecord!=NULL)
{
if (!m_pRecord->adoBOF)
{
m_pRecord->MoveFirst();
}
while(!m_pRecord->adoEOF)
{
for (int i=0; i<nFieldnum; i++)
{
varTemp = m_pRecord->GetCollect((_bstr_t)strFields[i]);
strResult[nRecordCnd][i] = (LPCSTR)_bstr_t(varTemp);
}
m_pRecord->MoveNext();
nRecordCnd++;
}
}
/* else
{
return 2;
}*/
}
catch (...)
{
AfxMessageBox("数据库错误");
return -1;
}
return 1;
}
int CADOConn::GetRecordCount(CString strTable, int &nCount, CString strCondition)
{
_RecordsetPtr m_pRecord = NULL;
int nCounter = 0;
CString m_sql;
m_sql = "select * from " + strTable + strCondition;
try
{
m_pRecord = GetRecordSet((_bstr_t)m_sql);
if (m_pRecord!=NULL)
{
if (!m_pRecord->adoBOF)
{
m_pRecord->MoveFirst();
}
while(!m_pRecord->adoEOF)
{
m_pRecord->MoveNext();
nCounter++;
}
}
nCount = nCounter;
}
catch (...)
{
AfxMessageBox("数据库错误");
return -1;
}
return 1;
}
//return -1:主键冲突/////////////////注意m_Storedata=VT_NULL的情况,要做处理
int CADOConn::InsertRecord(CString strTable, int nCount, CString *strFields,
CString *strValue,CString strKeyfield, CString strKey)
{
CString m_sql;
_RecordsetPtr m_pRecord;
_variant_t m_Storedata;
try
{
if (strKeyfield != "")
{
m_sql = "select * from " + strTable;
m_pRecord = GetRecordSet((_bstr_t)m_sql);
if (m_pRecord!=NULL)
{
if (!m_pRecord->adoBOF)
{
m_pRecord->MoveFirst();
}
while (!m_pRecord->adoEOF)
{
m_Storedata = m_pRecord->GetCollect((_bstr_t)strKeyfield);
if ((LPCSTR)_bstr_t(m_Storedata)==strKey)
{
return 0;
}
m_pRecord->MoveNext();
}
}
}
m_sql = "insert into " + strTable + " (";
for (int i=0; i<nCount-1; i++)
{
m_sql += strFields[i] + ",";
}
m_sql += strFields[nCount-1] + ") ";
m_sql += "values (";
for (i=0; i<nCount-1; i++)
{
m_sql += strValue[i] + ",";
}
m_sql += strValue[nCount-1] + ") ";
ExecuteSQL((_bstr_t)m_sql);
}
catch (...)
{
AfxMessageBox("数据库错误");
return -1;
}
return 1;
}
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_ADOCONN1_H__E411A6A3_90BA_4C07_8BC5_5F48FFF4DB07__INCLUDED_)
#define AFX_ADOCONN1_H__E411A6A3_90BA_4C07_8BC5_5F48FFF4DB07__INCLUDED_
//#include <ole2.h>
//#include <stdio.h>
//#include <conio.h>
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "sqlext.h"
//#import "d:\Program Files\Common Files\System\ado\msado15.dll"no_namespace rename("EOF","adoEOF")rename("BOF","adoBOF")
class CADOConn
{
public:
CADOConn();
virtual ~CADOConn();
public:
//ADODB::_ConnectionPtr m_pConnect
_ConnectionPtr m_pConnection;
_RecordsetPtr m_pRecordset;
public:
//初始化——连接数据库
static void OnInitDBConnect();
//执行查询
_RecordsetPtr& GetRecordSet(_bstr_t bstrSQL);
//Insetr Update _variant_t
BOOL ExecuteSQL(_bstr_t bstrSQL);
void ExitConnect();
//获得表长
int GetRecordCount(CString strTable, int &nCount, CString strCondition = _T(""));
//表名,待查字段名数组,待查字段个数,查询结果数组,查询条件“ where。。。”
int SelectRecordSet(CString strTable, CString *strFields,
int nFieldnum, CString **strResult, CString strCondition = _T(""));
int InsertRecord(CString strTable, int nCount, CString *strFields, CString *strValue,
CString strkeyfield = _T(""), CString strkey = _T(""));
};
#endif // !defined(AFX_ADOCONN1_H__E411A6A3_90BA_4C07_8BC5_5F48FFF4DB07__INCLUDED_)
.CPP文件如下:
// ADOConn.cpp: implementation of the CADOConn class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ADOConn.h"
//#include "ExamTest.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
//extern CLABMANAGEApp theApp;
CADOConn::CADOConn()
{
}
CADOConn::~CADOConn()
{
}
void CADOConn::OnInitDBConnect()
{
AfxMessageBox("start to connect!");
CString strUser;
CString strServer;
CString strPwd;
CString strConnection;
/*strUser = theApp.m_UserName;
strPwd = theApp.m_Password;
strServer = theApp.m_ServerName;*/
strServer = "QEQ";
strConnection = "Provider=SQLOLEDB;Server=";
strConnection+= strServer + ";Database=sturecord";
/*strConnection+= strUser + ";pwd=";
strConnection+= strPwd + ";";*/
::CoInitialize(NULL);
try
{
m_pConnection.CreateInstance(__uuidof(Connection));//******************
_bstr_t strConnect = (_bstr_t)strConnection;
m_pConnection->Open(strConnect,"","",adModeUnknown);//****************
}
catch(_com_error e)
{
AfxMessageBox(e.Description()+"系统退出!");
exit(0);
}
}
_RecordsetPtr& CADOConn::GetRecordSet(_bstr_t bstrSQL)
{
try
{
if (m_pConnection == NULL)
{
OnInitDBConnect();
}
m_pRecordset.CreateInstance(_uuidof(Recordset));
m_pRecordset->Open(bstrSQL, (_variant_t)m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);
}
catch (_com_error e)
{
AfxMessageBox(e.Description()+"系统退出!");
exit(0);
}
return m_pRecordset;
_variant_t var;
}
BOOL CADOConn::ExecuteSQL(_bstr_t bstrSQL)//************************
{
try
{
if (m_pConnection ==NULL)
{
AfxMessageBox("自动连接!");
OnInitDBConnect();
}
m_pConnection->Execute(bstrSQL,NULL,adCmdText);
}
catch (_com_error e)
{
AfxMessageBox(e.Description()+"系统退出!");
exit(0);
return false;
}
return true;
}
void CADOConn::ExitConnect()
{
if (m_pRecordset != NULL)
{
m_pRecordset->Close();
m_pConnection->Close();
::CoUninitialize();
}
}
////注意m_Storedata=VT_NULL的情况,要做处理, 暂不处理
int CADOConn::SelectRecordSet(CString strTable, CString *strFields, int nFieldnum,
CString **strResult, CString strCondition)
{
CString m_sql;
int nRecordCnd = 0;
_variant_t varTemp;
_RecordsetPtr m_pRecord = NULL;
m_sql = "select * from " + strTable + " " + strCondition;
try
{
m_pRecord = GetRecordSet((_bstr_t)m_sql);
if (m_pRecord!=NULL)
{
if (!m_pRecord->adoBOF)
{
m_pRecord->MoveFirst();
}
while(!m_pRecord->adoEOF)
{
for (int i=0; i<nFieldnum; i++)
{
varTemp = m_pRecord->GetCollect((_bstr_t)strFields[i]);
strResult[nRecordCnd][i] = (LPCSTR)_bstr_t(varTemp);
}
m_pRecord->MoveNext();
nRecordCnd++;
}
}
/* else
{
return 2;
}*/
}
catch (...)
{
AfxMessageBox("数据库错误");
return -1;
}
return 1;
}
int CADOConn::GetRecordCount(CString strTable, int &nCount, CString strCondition)
{
_RecordsetPtr m_pRecord = NULL;
int nCounter = 0;
CString m_sql;
m_sql = "select * from " + strTable + strCondition;
try
{
m_pRecord = GetRecordSet((_bstr_t)m_sql);
if (m_pRecord!=NULL)
{
if (!m_pRecord->adoBOF)
{
m_pRecord->MoveFirst();
}
while(!m_pRecord->adoEOF)
{
m_pRecord->MoveNext();
nCounter++;
}
}
nCount = nCounter;
}
catch (...)
{
AfxMessageBox("数据库错误");
return -1;
}
return 1;
}
//return -1:主键冲突/////////////////注意m_Storedata=VT_NULL的情况,要做处理
int CADOConn::InsertRecord(CString strTable, int nCount, CString *strFields,
CString *strValue,CString strKeyfield, CString strKey)
{
CString m_sql;
_RecordsetPtr m_pRecord;
_variant_t m_Storedata;
try
{
if (strKeyfield != "")
{
m_sql = "select * from " + strTable;
m_pRecord = GetRecordSet((_bstr_t)m_sql);
if (m_pRecord!=NULL)
{
if (!m_pRecord->adoBOF)
{
m_pRecord->MoveFirst();
}
while (!m_pRecord->adoEOF)
{
m_Storedata = m_pRecord->GetCollect((_bstr_t)strKeyfield);
if ((LPCSTR)_bstr_t(m_Storedata)==strKey)
{
return 0;
}
m_pRecord->MoveNext();
}
}
}
m_sql = "insert into " + strTable + " (";
for (int i=0; i<nCount-1; i++)
{
m_sql += strFields[i] + ",";
}
m_sql += strFields[nCount-1] + ") ";
m_sql += "values (";
for (i=0; i<nCount-1; i++)
{
m_sql += strValue[i] + ",";
}
m_sql += strValue[nCount-1] + ") ";
ExecuteSQL((_bstr_t)m_sql);
}
catch (...)
{
AfxMessageBox("数据库错误");
return -1;
}
return 1;
}
#4
ADO不会用,我是个用MFC的新手,有没有更简单的办法啊?
#5
如果你对MFC不熟悉,可以先用Console来写程序,学习ADO。
下面是一个Console的程序,是演示ADO的MoveFirst等功能的使用。
这是MSDN的例子,在MSDN里还有很多其它的例子,如果你买两三本ADO的书,再结合这些例子,会很快上手ADO的。另外你还需要一个数据库软件配合,即然你是新手,可以使用SQL Server 2000。这样会方便很多。祝你好运
// BeginMoveFirstCpp
#include <ole2.h>
#include <stdio.h>
#import "c:\Program Files\Common Files\System\ADO\msado15.dll" \
no_namespace rename("EOF", "EndOfFile")
// Function declarations
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void MoveFirstX();
void MoveAny(int intChoice, _RecordsetPtr pRstTemp);
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
/////////////////////////////////
// Main Function //
/////////////////////////////////
void main()
{
if(FAILED(::CoInitialize(NULL)))
return;
MoveFirstX();
::CoUninitialize();
}
//////////////////////////////////////
// MoveFirstX Function //
//////////////////////////////////////
void MoveFirstX()
{
HRESULT hr = S_OK;
_RecordsetPtr pRstAuthors = NULL;
_bstr_t strCnn("Provider='sqloledb';Data Source='MySqlServer';"
"Initial Catalog='pubs';Integrated Security='SSPI';");
_bstr_t strMessage("UPDATE Titles SET Type = "
"'psychology' WHERE Type = 'self_help'");
int intCommand = 0;
// Temporary string variable for type conversion for printing.
_bstr_t bstrFName;
_bstr_t bstrLName;
try
{
// Open recordset from Authors table.
TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));
pRstAuthors->CursorType = adOpenStatic;
// Use client cursor to enable AbsolutePosition property.
pRstAuthors->CursorLocation = adUseClient;
pRstAuthors->Open("Authors", strCnn, adOpenStatic,
adLockBatchOptimistic, adCmdTable);
// Show current record information and get user's method choice.
while (true) // Continuous loop.
{
// Convert variant string to convertable string type.
bstrFName = pRstAuthors->Fields->Item["au_fName"]->Value;
bstrLName = pRstAuthors->Fields->Item["au_lName"]->Value;
printf("Name: %s %s\n Record %d of %d\n\n",
(LPCSTR) bstrFName,
(LPCSTR) bstrLName,
pRstAuthors->AbsolutePosition,
pRstAuthors->RecordCount);
printf("[1 - MoveFirst, 2 - MoveLast, \n");
printf(" 3 - MoveNext, 4 - MovePrevious, 5 - Quit]\n");
scanf("%d", &intCommand);
if ((intCommand < 1) || (intCommand > 4))
break; // Out of range entry exits program loop.
// Call method based on user's input.
MoveAny(intCommand, pRstAuthors);
}
}
catch (_com_error &e)
{
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstAuthors->GetActiveConnection();
// GetActiveConnection returns connect string if connection
// is not open, else returns Connection object.
switch(vtConnect.vt)
{
case VT_BSTR:
PrintComError(e);
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
}
// Clean up objects before exit.
if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
}
/////////////////////////////////
// MoveAny Function //
/////////////////////////////////
void MoveAny(int intChoice, _RecordsetPtr pRstTemp)
{
// Use specified method, trapping for BOF and EOF
try
{
switch(intChoice)
{
case 1:
pRstTemp->MoveFirst();
break;
case 2:
pRstTemp->MoveLast();
break;
case 3:
pRstTemp->MoveNext();
if (pRstTemp->EndOfFile)
{
printf("\nAlready at end of recordset!\n");
pRstTemp->MoveLast();
} //End If
break;
case 4:
pRstTemp->MovePrevious();
if (pRstTemp->BOF)
{
printf("\nAlready at beginning of recordset!\n");
pRstTemp->MoveFirst();
}
break;
default:
;
}
}
catch(_com_error &e)
{
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstTemp->GetActiveConnection();
// GetActiveConnection returns connect string if connection
// is not open, else returns Connection object.
switch(vtConnect.vt)
{
case VT_BSTR:
PrintComError(e);
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
}
}
////////////////////////////////////////////
// PrintProviderError Function //
////////////////////////////////////////////
void PrintProviderError(_ConnectionPtr pConnection)
{
// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;
if( (pConnection->Errors->Count) > 0)
{
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount - 1.
for(long i = 0; i < nCount; i++)
{
pErr = pConnection->Errors->GetItem(i);
printf("\t Error number: %x\t%s", pErr->Number,
pErr->Description);
}
}
}
//////////////////////////////////////
// PrintComError Function //
//////////////////////////////////////
void PrintComError(_com_error &e)
{
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
// Print Com errors.
printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}
// EndMoveFirstCpp
下面是一个Console的程序,是演示ADO的MoveFirst等功能的使用。
这是MSDN的例子,在MSDN里还有很多其它的例子,如果你买两三本ADO的书,再结合这些例子,会很快上手ADO的。另外你还需要一个数据库软件配合,即然你是新手,可以使用SQL Server 2000。这样会方便很多。祝你好运
// BeginMoveFirstCpp
#include <ole2.h>
#include <stdio.h>
#import "c:\Program Files\Common Files\System\ADO\msado15.dll" \
no_namespace rename("EOF", "EndOfFile")
// Function declarations
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void MoveFirstX();
void MoveAny(int intChoice, _RecordsetPtr pRstTemp);
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
/////////////////////////////////
// Main Function //
/////////////////////////////////
void main()
{
if(FAILED(::CoInitialize(NULL)))
return;
MoveFirstX();
::CoUninitialize();
}
//////////////////////////////////////
// MoveFirstX Function //
//////////////////////////////////////
void MoveFirstX()
{
HRESULT hr = S_OK;
_RecordsetPtr pRstAuthors = NULL;
_bstr_t strCnn("Provider='sqloledb';Data Source='MySqlServer';"
"Initial Catalog='pubs';Integrated Security='SSPI';");
_bstr_t strMessage("UPDATE Titles SET Type = "
"'psychology' WHERE Type = 'self_help'");
int intCommand = 0;
// Temporary string variable for type conversion for printing.
_bstr_t bstrFName;
_bstr_t bstrLName;
try
{
// Open recordset from Authors table.
TESTHR(pRstAuthors.CreateInstance(__uuidof(Recordset)));
pRstAuthors->CursorType = adOpenStatic;
// Use client cursor to enable AbsolutePosition property.
pRstAuthors->CursorLocation = adUseClient;
pRstAuthors->Open("Authors", strCnn, adOpenStatic,
adLockBatchOptimistic, adCmdTable);
// Show current record information and get user's method choice.
while (true) // Continuous loop.
{
// Convert variant string to convertable string type.
bstrFName = pRstAuthors->Fields->Item["au_fName"]->Value;
bstrLName = pRstAuthors->Fields->Item["au_lName"]->Value;
printf("Name: %s %s\n Record %d of %d\n\n",
(LPCSTR) bstrFName,
(LPCSTR) bstrLName,
pRstAuthors->AbsolutePosition,
pRstAuthors->RecordCount);
printf("[1 - MoveFirst, 2 - MoveLast, \n");
printf(" 3 - MoveNext, 4 - MovePrevious, 5 - Quit]\n");
scanf("%d", &intCommand);
if ((intCommand < 1) || (intCommand > 4))
break; // Out of range entry exits program loop.
// Call method based on user's input.
MoveAny(intCommand, pRstAuthors);
}
}
catch (_com_error &e)
{
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstAuthors->GetActiveConnection();
// GetActiveConnection returns connect string if connection
// is not open, else returns Connection object.
switch(vtConnect.vt)
{
case VT_BSTR:
PrintComError(e);
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
}
// Clean up objects before exit.
if (pRstAuthors)
if (pRstAuthors->State == adStateOpen)
pRstAuthors->Close();
}
/////////////////////////////////
// MoveAny Function //
/////////////////////////////////
void MoveAny(int intChoice, _RecordsetPtr pRstTemp)
{
// Use specified method, trapping for BOF and EOF
try
{
switch(intChoice)
{
case 1:
pRstTemp->MoveFirst();
break;
case 2:
pRstTemp->MoveLast();
break;
case 3:
pRstTemp->MoveNext();
if (pRstTemp->EndOfFile)
{
printf("\nAlready at end of recordset!\n");
pRstTemp->MoveLast();
} //End If
break;
case 4:
pRstTemp->MovePrevious();
if (pRstTemp->BOF)
{
printf("\nAlready at beginning of recordset!\n");
pRstTemp->MoveFirst();
}
break;
default:
;
}
}
catch(_com_error &e)
{
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = pRstTemp->GetActiveConnection();
// GetActiveConnection returns connect string if connection
// is not open, else returns Connection object.
switch(vtConnect.vt)
{
case VT_BSTR:
PrintComError(e);
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
}
}
////////////////////////////////////////////
// PrintProviderError Function //
////////////////////////////////////////////
void PrintProviderError(_ConnectionPtr pConnection)
{
// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;
if( (pConnection->Errors->Count) > 0)
{
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount - 1.
for(long i = 0; i < nCount; i++)
{
pErr = pConnection->Errors->GetItem(i);
printf("\t Error number: %x\t%s", pErr->Number,
pErr->Description);
}
}
}
//////////////////////////////////////
// PrintComError Function //
//////////////////////////////////////
void PrintComError(_com_error &e)
{
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
// Print Com errors.
printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);
}
// EndMoveFirstCpp
#6
上面给你的两段代码,是我使用的完整代码:
你在你的工程中增加一个新类把,上面的.H文件加到你的头文件
把.CPP文件加入到你的CPP文件中,
然后那个类中要用到数据库查询,就把这个新类INCLUDE进去,然后调用不是很难的....给你一段调用的实例,供参考:
//向表PUB_XSQDB写入以上信息
CADOConn myInsert;
CString mySQL;
CString insertfilds;
insertfilds = "insert into PUB_XSQDB(DLH_PK,BM,YHM,QDSJ,QDRQ,SYPTH_PK,SYSMC) VALUES(";
CString strfgf1;
strfgf1 = "'";
CString strfgf2;
strfgf2 = "',";
CString sysmc;
sysmc = "'电工实验室'";
CString ykh;
ykh = ")";
mySQL = insertfilds +strfgf1+studentxh+strfgf2+ strfgf1+strbj+ strfgf2 + strfgf1 + studentname + strfgf2 + strfgf1 +s_currenttime+strfgf2+strfgf1+s_currentdate+strfgf2 + strfgf1+labinfo[i].labnumber +strfgf2+ sysmc +ykh;
消息myInsert.ExecuteSQL((_bstr_t)mySQL);
mySQL就是一个SQL插入语句,再不会用的话帮为不了你了....多找人问下更直接论坛里很难说清楚!
你在你的工程中增加一个新类把,上面的.H文件加到你的头文件
把.CPP文件加入到你的CPP文件中,
然后那个类中要用到数据库查询,就把这个新类INCLUDE进去,然后调用不是很难的....给你一段调用的实例,供参考:
//向表PUB_XSQDB写入以上信息
CADOConn myInsert;
CString mySQL;
CString insertfilds;
insertfilds = "insert into PUB_XSQDB(DLH_PK,BM,YHM,QDSJ,QDRQ,SYPTH_PK,SYSMC) VALUES(";
CString strfgf1;
strfgf1 = "'";
CString strfgf2;
strfgf2 = "',";
CString sysmc;
sysmc = "'电工实验室'";
CString ykh;
ykh = ")";
mySQL = insertfilds +strfgf1+studentxh+strfgf2+ strfgf1+strbj+ strfgf2 + strfgf1 + studentname + strfgf2 + strfgf1 +s_currenttime+strfgf2+strfgf1+s_currentdate+strfgf2 + strfgf1+labinfo[i].labnumber +strfgf2+ sysmc +ykh;
消息myInsert.ExecuteSQL((_bstr_t)mySQL);
mySQL就是一个SQL插入语句,再不会用的话帮为不了你了....多找人问下更直接论坛里很难说清楚!