怎么使用MFC操作本地数据库中的一个表
如何使用MFC操作本地数据库中的一个表?
这是我数据库中的一个表
我想通过MFC把这个表中006邓的性别改为"男"
具体代码怎么写?
------解决思路----------------------
用ado去执行sql即可
------解决思路----------------------
推荐CAdo这个组件
------解决思路----------------------
这样初始化数据库就ok了,接着就可以访问数据库中的某张表
首先定义2个函数
函数调用方法
这是我数据库中的一个表
我想通过MFC把这个表中006邓的性别改为"男"
具体代码怎么写?
------解决思路----------------------
用ado去执行sql即可
------解决思路----------------------
推荐CAdo这个组件
------解决思路----------------------
stdafx.h中
#import "msado15.dll" no_namespace rename ("EOF", "adoEOF")
工程头文件中定义
_ConnectionPtr m_pConnection;
_CommandPtr m_pCommand;
_RecordsetPtr m_pRecordset;
BOOL Initialization(CString name , CString pass , CString ip , int port, CString tables);
void dump_com_error(_com_error &e);
工程源文件中定义
BOOL xxxxxx::Initialization(CString name , CString pass , CString ip , int port, CString tables)
{
m_pConnection = NULL;
m_pRecordset = NULL;
m_pConnection.CreateInstance(__uuidof(Connection));
CString strport;
strport.Format(_T("%d"),port);
::CoInitialize(NULL);
try
{
if (!m_pConnection->State)
{
m_pConnection->Open(_bstr_t(_T("Provider=SQLOLEDB.1;Persist Security Info=False;\
User ID=sa;Initial Catalog="+tables+";Data Source="+ip+","+strport+";Network Library=DBMSSOCN")),\
_bstr_t(name), _bstr_t(pass), adOpenUnspecified);
}
}
catch(_com_error& e)
{
dump_com_error(e);
return FALSE;
}
return TRUE;
}
void xxxxxx::dump_com_error(_com_error &e)
{
CString ErrorStr;
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());
ErrorStr.Format(_T("\n\tADO Error\n\tCode = %08lx\n\tCode meaning = %s\n\tSource = %s\n\tDescription = %s\n\n"),
e.Error(), e.ErrorMessage(), (LPCTSTR)bstrSource, (LPCTSTR)bstrDescription );
::OutputDebugString((LPCTSTR)ErrorStr);
#ifdef _DEBUG
AfxMessageBox(ErrorStr, MB_OK
------解决思路----------------------
MB_ICONERROR);
#endif
}
OnInitDialog()
{
......
Initialization(L"数据库用户名",L"数据库密码",L"连接数据库的IP地址",1433,L"数据库名称");
......
}
这样初始化数据库就ok了,接着就可以访问数据库中的某张表
首先定义2个函数
//这函数用来执行sql语句
BOOL SqlExe(_variant_t sql)
//这个函数专门用来读取列名
CString GetField(CString strColumnName)
BOOL SqlExe(_variant_t sql)
{
m_pRecordset.CreateInstance(__uuidof(Recordset));
try
{
if(m_pRecordset->State != 0 )
m_pRecordset->Close();
m_pRecordset->Open(sql,
m_pConnection.GetInterfacePtr(),
adOpenDynamic,
adLockOptimistic,
adCmdText);
return TRUE;
}
catch(_com_error& e)
{
dump_com_error(e);
}
return FALSE;
}
// 读取数据库列名
CString GetField_s(CString strColumnName) //读列名
{
_variant_t var;
try
{
var = m_pRecordset->GetCollect((_variant_t)strColumnName);
if(var.vt != VT_NULL)
return (CString)(var);
else
return L"";
}
catch(_com_error& e)
{
CString str;
str.Format(_T("%s"),e.ErrorMessage());
return (CString)(var = _T(""));
}
}
函数调用方法
sqldb = L"select * from table_ab";
sqlexe(sqldb);
//执行完以后,用
cstring a = GetField(L"name");