包含了头文件和cpp文件后,可以这样
CADORecordset* pRs = new CADORecordset((static_cast<CFrenchApp *>(AfxGetApp()))->g_pDb)
Sql1="select word,wordtype,meaning,tag,id from word "+Where
int i=0
if(pRs->Open((LPCTSTR)Sql1))
{
while(!pRs->IsEof())
{
pRs->GetFieldValue(0,word[i].word)
pRs->GetFieldValue(3,word[i].tag)
pRs->GetFieldValue(1,word[i].wordtype)
pRs->GetFieldValue(2,word[i].meaning)
pRs->GetFieldValue(4,word[i].id)
pRs->MoveNext()
i++
}
pRs->Close()
}
m_max=i
m_cur=0
delete pRs
这样就可以得到数据库里的东西
对于SQL Server数据库,C++使用MFC库,主要有两种方法可以连接sql数据库
1.利用ADO连接:
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
//必须import这个dll,这个文件通常放在C:\Program Files\Common Files\System\ado路径下.
_ConnectionPtr m_ptrConnection//数据库连接对象
构造函数中添加如下语句
m_ptrConnection = NULL
::CoInitialize(NULL)
//连接数据库的主要代码
BOOL DataVisitor::ConnectDataBase(_bstr_t connectionStr)
{
/*
Added by stone. If IDOConnection has not been set up,then create one.
*/
if(m_ptrConnection == NULL)
{
HRESULT hr = m_ptrConnection.CreateInstance(__uuidof(Connection))
if (FAILED(hr))
{
return FALSE
}
else
{
_bstr_t strConnect = connectionStr
//"Provider=SQLOLEDBServer=(local)Database=navigationuid=sapwd=3277625"
m_ptrConnection->CursorLocation = adUseClient
m_ptrConnection->IsolationLevel = adXactReadCommitted
try
{
m_ptrConnection->Open(strConnect,"","",adModeUnknown)
return TRUE
}
catch (_com_error e)
{
// AfxMessageBox((char *)e.Description())
return FALSE
}
}
}
return TRUE
}
2. 利用ODBC连接
#include <afxdao.h>
CDaoDatabase *MyDataBase
BOOL MyDB_OperSqL::Open_MyDatabase(CString connstr)
{
try
{
if (MyDataBase == NULL)
{
MyDataBase = new CDaoDatabase()
}
MyDataBase->Open(NULL,0,0,connstr)
}
catch( CDaoException* e )
{
CString message = _T("MyDB_OperSqL 数据库异常: ")
message += e->m_pErrorInfo->m_strDescription
char info[400]
sprintf(info,message)
DispErrorMessage(info,__LINE__)
e->Delete( )
return FALSE
}
catch (CMemoryException *e)
{
DispErrorMessage("MyDB_OperSqL 内存异常!",__LINE__)
e->Delete( )
return FALSE
}
catch(...)
{
DispErrorMessage("MyDB_OperSqL 其它异常!",__LINE__)
return FALSE
}
return TRUE
}
这里的连接字符串connstr一般是如下内容
"ODBCDRIVER={SQL Server}SERVER=(local)DATABASE=yourDataBaseUID=yourIDPWD=yourPassword"
如果直接用Microsoft ADO Datebase Control控件的话,连接字串可以自己生成,在控件的属性里面找到拷贝就行,这种最简单
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)