第一次接触数据库

谢攀琪 2011-10-13 12:02:52
求MFC连接数据库的详细方法
我数据库用的是SQL Server 2008

别怕罗嗦,只怕不够详细
...全文
119 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
calm_keep 2011-10-14
  • 打赏
  • 举报
回复
google到处都是
夜行人 2011-10-14
  • 打赏
  • 举报
回复
http://www.pudn.com/downloads385/sourcecode/windows/database/detail1655327.html这里有个ADO的实例
CppCoder 2011-10-13
  • 打赏
  • 举报
回复
连接数据库实现就几句话,主要是连接串的配置,要根据自己的环境设置(用户、密码、驱动。。。)
Ginie 2011-10-13
  • 打赏
  • 举报
回复

bool CMyDataBase::DeleteUserOfSelected(CString UserID)
{

CString strSql;
_variant_t RecordsAffected;

strSql.Format("DELETE FROM users WHERE UserID = %d",atoi(UserID)); // strSql="DELETE FROM users WHERE UserID = 10";
//AfxMessageBox(strSql);
m_pConnection->Execute((_bstr_t)strSql,&RecordsAffected,adCmdText);
AfxMessageBox(strSql);
return TRUE;
}

void CMyDataBase::SaveNewUserToDataBase()
{
//实际此函数应采用一个结构体传入参数

// InitDataBase();//这是必须的

CString strSql;

_variant_t RecordsAffected;
CString m_1,m_2,m_3;
m_1="林妹妹";
m_2="13579";
m_3="小林";

strSql.Format("INSERT INTO users(UserName,LoginPassWord,DisplayName) VALUES ('%s','%s','%s')",m_1,m_2,m_3);
m_pConnection->Execute((_bstr_t)strSql,&RecordsAffected,adCmdText);

}

bool CMyDataBase::InitDataBase()
{
//初始化数据库连接


HRESULT hr;
try
{
hr = m_pConnection.CreateInstance("ADODB.Connection");//创建Connection对象
if(SUCCEEDED(hr))
{
hr = m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=DataBase.mdb","","",adModeUnknown);///连接数据库
//hr = m_pConnection->Open("studb","","",adModeUnknown);
}
}
catch(_com_error e)///捕捉异常
{
CString errormessage;
errormessage.Format("连接数据库失败!\r\n错误信息:%s",e.ErrorMessage());
AfxMessageBox(errormessage);///显示错误信息
}
_variant_t RecordsAffected;
//m_pConnection->Execute("CREATE TABLE studentinfo(stuNo TEXT,stuname TEXT,stuaddress TEXT,stuphone TEXT)",&RecordsAffected,adCmdText);
// CString strSQL;

// CString s1,s2;

// strSQL.Format("INSERT INTO users(UserName,PassWord) VALUES ('%s','%s')","abc","123456");
// strSQL.Format("INSERT INTO users(UserName,LoginPassWord,DisplayName) VALUES ('%s','%s','%s')","东方不败","123456","东方妹妹");

// m_pConnection->Execute((_bstr_t)strSQL,&RecordsAffected,adCmdText);
return TRUE;
}



//把会议室列表的初始化打包到这儿
void CMyDataBase::InitConfListCtrl(CListCtrl* pListCtrl)
{

/*直接插入行测试指针
pListCtrl->InsertItem(0, 0);//插入行
pListCtrl->SetItemText(0, 1, "公共聊天室");//设置数据
pListCtrl->SetItemText(0, 2, "50");
pListCtrl->SetItemText(0, 3, "5");
pListCtrl->SetItemText(0, 4, "2010-12-1");
pListCtrl->SetItemText(0, 5, "2010-12-1");
*/

InitDataBase();//这是必须的

//设置风格
LONG lStyle;
lStyle = GetWindowLong(pListCtrl->m_hWnd, GWL_STYLE);//获取当前窗口style
lStyle &= ~LVS_TYPEMASK; //清除显示方式位
lStyle |= LVS_REPORT; //设置style
SetWindowLong(pListCtrl->m_hWnd, GWL_STYLE, lStyle);//设置style

DWORD dwStyle = pListCtrl->GetExtendedStyle();
dwStyle |= LVS_EX_FULLROWSELECT;//选中某行使整行高亮(只适用与report风格的listctrl)
dwStyle |= LVS_EX_GRIDLINES;//网格线(只适用与report风格的listctrl)
//dwStyle |= LVS_EX_CHECKBOXES;//item前生成checkbox控件
pListCtrl->SetExtendedStyle(dwStyle); //设置扩展风格

pListCtrl->InsertColumn( 0, "ID", LVCFMT_LEFT, 0 );//插入列,将宽度设置成0,在外观上就看不到此列,用来存放会员号
pListCtrl->InsertColumn( 1, "ID", LVCFMT_LEFT, 60 );
pListCtrl->InsertColumn( 2, "会议室名称", LVCFMT_LEFT, 100 );
pListCtrl->InsertColumn( 3, "容量", LVCFMT_LEFT, 60 );
pListCtrl->InsertColumn( 4, "在线", LVCFMT_LEFT, 60 );
pListCtrl->InsertColumn( 5, "开始", LVCFMT_LEFT, 140 );
pListCtrl->InsertColumn( 6, "结束", LVCFMT_LEFT, 140 );

HRESULT hr;
_RecordsetPtr pRentRecordset;
hr=pRentRecordset.CreateInstance(__uuidof(Recordset));
if(FAILED(hr))
{
AfxMessageBox("createinstance of Recordset failed!\n can`t initiate List control!");
return;
}



CString strSql;
_variant_t var;
CString strValue;
int curItem=0;
strSql="SELECT * FROM Conf";



try
{
hr=pRentRecordset->Open(_variant_t(strSql),
m_pConnection.GetInterfacePtr(),
adOpenDynamic,
adLockOptimistic,
adCmdText);
if(SUCCEEDED(hr))
{
while(!pRentRecordset->adoEOF)
{

var = pRentRecordset->GetCollect((long)0);
if(var.vt != VT_NULL)
strValue = (LPCSTR)_bstr_t(var);
pListCtrl->InsertItem(curItem,strValue);

var = pRentRecordset->GetCollect("ConfID");
if(var.vt != VT_NULL)
strValue = (LPCSTR)_bstr_t(var);
pListCtrl->SetItemText(curItem,1,strValue);

var = pRentRecordset->GetCollect("ConfName");
if(var.vt != VT_NULL)
strValue = (LPCSTR)_bstr_t(var);
pListCtrl->SetItemText(curItem,2,strValue);

var = pRentRecordset->GetCollect("MaxNum");
if(var.vt != VT_NULL)
strValue = (LPCSTR)_bstr_t(var);
pListCtrl->SetItemText(curItem,3,strValue);

var = pRentRecordset->GetCollect("OnlineNum");
if(var.vt != VT_NULL)
strValue = (LPCSTR)_bstr_t(var);
pListCtrl->SetItemText(curItem,4,strValue);

var = pRentRecordset->GetCollect("StartTime");
if(var.vt != VT_NULL)
strValue = (LPCSTR)_bstr_t(var);
pListCtrl->SetItemText(curItem,5,strValue);

var = pRentRecordset->GetCollect("EndTime");
if(var.vt != VT_NULL)
strValue = (LPCSTR)_bstr_t(var);
pListCtrl->SetItemText(curItem,6,strValue);


pRentRecordset->MoveNext();
curItem++;
}
}
else
{
AfxMessageBox("Open recordset fail!");
}
}
catch(_com_error *e)
{
AfxMessageBox(e->ErrorMessage());
return;
}


pRentRecordset->Close();
pRentRecordset=NULL;

}


呔妖怪来嘛 2011-10-13
  • 打赏
  • 举报
回复
Ionstorm2 2011-10-13
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 chinatcp 的回复:]

C/C++ code



#include <afxdb.h>
void CDlg::OnStnClickedButton1()
{
CDatabase conn;
conn.OpenEx(L"Driver={SQL Server};server=192.168.0.101;uid=sa;pwd=123456;database=db1",CDatabase::openRead……
[/Quote]

++,这是ODBC的连接方法,还可以用ODBC API或者ADO等方法去连接
不二星空 2011-10-13
  • 打赏
  • 举报
回复
建议学习ADO的方式连接数据库,具体的网上有一大堆资料
ljn398431 2011-10-13
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 chinatcp 的回复:]
C/C++ code



#include <afxdb.h>
void CDlg::OnStnClickedButton1()
{
CDatabase conn;
conn.OpenEx(L"Driver={SQL Server};server=192.168.0.101;uid=sa;pwd=123456;database=db1",CDatabase::op……
[/Quote]这个就可以啊
alpha.5 2011-10-13
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 chinatcp 的回复:]
C/C++ code
#include <afxdb.h>
void CDlg::OnStnClickedButton1()
{
CDatabase conn;
conn.OpenEx(L"Driver={SQL Server};server=192.168.0.101;uid=sa;pwd=123456;database=db1",CDatabase::openRead……
[/Quote]
++
这个连接方法都有很多种的..
adw其 2011-10-13
  • 打赏
  • 举报
回复
关键几个步骤.(用ADO链接)
1\添加msado15.dll.
在stdafx.h中添加如下如句
#import"C:\Program Files\Common Files\System\ado\msado15.dll"\
no_namespace\
rename("EOF","adoEOF")

2\初始化COM
如果是使用dialog创建的工程需要添加如下语句,如果是SDI中的formView的话,则不需要,架构自动添加了
在CSqlConnect06App::InitInstance()中添加如如下语句:
if (!SUCCEEDED(CoInitialize(NULL)))
{
::AfxMessageBox(_T("初始化COM失败!"));
return FALSE;
}

一定要在对话框创建语句之前添加.
CSqlConnect06Dlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
就是这几句之前.
3\建立链接
在dlg类中添加成员变量

_ConnectionPtr m_pConnection;
_CommandPtr m_pCommand;
_RecordsetPtr m_pRecordset;

在dlg类中添加两个函数 OpenDatabase和CloseDatabase
BOOL CSqlConnect06Dlg::OpenDatabase(LPCTSTR lpszConnect, long nOptions)
{
ASSERT(m_pConnection!=NULL);
ASSERT(lpszConnect!=NULL);
ASSERT(AfxIsValidString(lpszConnect));
try
{
return SUCCEEDED(m_pConnection->Open(_bstr_t(lpszConnect),_T("sa"),_T(""),nOptions));
}
catch(_com_error& e)
{
TRACE(_T("%s\n"),e.ErrorMessage());
return FALSE;
}
}


BOOL CSqlConnect06Dlg::CloseDatabase(void)
{
ASSERT(m_pConnection!=NULL);
try
{
if (m_pConnection->State& adStateOpen)
{
return SUCCEEDED(m_pConnection->Close());
}
else
{
return TRUE;
}
}
catch(_com_error& e)
{
TRACE(_T("%s\n"),e.ErrorMessage());
return FALSE;
}
//return 0;
}

在dlg类的构造函数中添加如下初始化语句
if (!SUCCEEDED(m_pConnection.CreateInstance(__uuidof(Connection))))
{
m_pConnection=NULL;
TRACE(_T("Database CreateInSTance Failed!"));
}
if (!SUCCEEDED(m_pRecordset.CreateInstance(__uuidof(Recordset))))
{
m_pRecordset=NULL;
TRACE(_T("Recordset CreateInstance Failed!"));
}
if (!SUCCEEDED(m_pCommand.CreateInstance(__uuidof(Command))))
{
m_pCommand=NULL;
TRACE(_T("Command CreateInstance Failed!"));
}
CString strConnect=_T("Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=DB_jiecai;Data Source=ADW");
if (!OpenDatabase(strConnect,adModeUnknown))
{
AfxMessageBox(_T("数据库打开失败"));
return;
}
m_pCommand->ActiveConnection=m_pConnection;
}

在析构函中添加
CSqlConnect06Dlg::~CSqlConnect06Dlg()
{
m_pConnection->Close();
}


在这时介绍一个获取链接语句的好方法:
CString strConnect=_T("Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=DB_jiecai;Data Source=ADW");

新建一个txt文件,将其后缀改为udl双击打开它.在第一个选项卡(提供程序)中选择Microsoft OLE DB provider for SQL Server.在第二个选项卡选择服务器名称,输入链接的用户名称和密码,选择你要链接的数据库,点测试连接.成功后点确定.
将文件重新命名为txt文件,打开,文件中的最后一句就是连接语句了.

本人也正在学习数据库方面的编程,在这里权当复习了.
罗平 2011-10-13
  • 打赏
  • 举报
回复



#include <afxdb.h>
void CDlg::OnStnClickedButton1()
{
CDatabase conn;
conn.OpenEx(L"Driver={SQL Server};server=192.168.0.101;uid=sa;pwd=123456;database=db1",CDatabase::openReadOnly|CDatabase::noOdbcDialog);
CRecordset rs(&conn);
rs.Open(CRecordset::forwardOnly,L"select * from table",CRecordset::readOnly);
while(!rs.IsEOF()){
CString sFieldValue;
rs.GetFieldValue(L"sFieldName",sFieldValue);
MessageBox(sFieldValue);
rs.MoveNext();
}
}

4,011

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 数据库
社区管理员
  • 数据库
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧