在MFC中连接SQL Server数据库,并对表进行操作(超简单)

必要准备

首先必须有你的数据库,以及表。我的电脑名字是LZW-GOOD,登录用户名是sa。
在这里插入图片描述
我这里使用的数据库是test0,表是Student。
在这里插入图片描述

需要包含的头文件


#include "afxdialogex.h"
#include <icrsint.h>
#include <windows.h>  
#include <sqltypes.h>  
#include <sql.h>  
#include <sqlext.h>
#import "c:\program files\common files\system\ado\msado15.dll"  no_namespace rename("EOF", "adoEOF")

如果大家运行时,抛出了异常,多半是因为sql语句错了。
也有可能是插入时主键约束等原因
我下方的代码不可以直接运行,需要大家修改其中的sql语句,也就是其中的字符串。

连接数据库

	//初始化指针
	_ConnectionPtr pMyConnect = NULL;
	HRESULT hr = pMyConnect.CreateInstance(__uuidof(Connection));
	if (FAILED(hr))
		return;
	//初始化连接字符串
	_bstr_t strConnect = "Driver={sql server};server=127.0.0.1;uid=sa;pwd=123456;database=test0;";
	//执行连接
	try
	{
		// 调用Open方法
		pMyConnect->Open(strConnect, "", "", NULL);
	}
	catch (_com_error &e) //连接异常
	{
		MessageBox(e.Description(), TEXT("提示"), MB_OK | MB_ICONINFORMATION);
	}

如果没有弹出对话框提示异常,表明连接成功

执行sql语句

查询

	//初始化Recordset指针
	_RecordsetPtr pRecordset;
	pRecordset.CreateInstance(__uuidof(Recordset));
	//查询
	CString strsql = TEXT("select * from student");
	pRecordset = pMyConnect->Execute(_bstr_t(strsql), NULL, adCmdText);//将查询结果导入pRecordset数据容器
	
	//遍历并读取sname列的记录并输出
	while (!pRecordset->adoEOF)
	{
		CString temp = (TCHAR *)(_bstr_t)pRecordset->GetFields()->GetItem("sname")->Value; 
		AfxMessageBox(temp);//以对话框显示所有sname
		//这里添加你的判断代码
		

		pRecordset->MoveNext();
	}

遍历弹出的对话框
在这里插入图片描述
在这里插入图片描述
等等…

修改

	//修改
	strsql = TEXT("update student set sname ='爸爸' where sname='王敏'");
	pRecordset = pMyConnect->Execute(_bstr_t(strsql), NULL, adCmdText);

插入

	//以常量插入
	strsql = TEXT("insert into student values('001','测试','男',20,'ABC')");
	pRecordset = pMyConnect->Execute(_bstr_t(strsql), NULL, adCmdText);

	//以变量插入
	CString id = TEXT("002");
	CString name=TEXT("测试");
	CString sex = TEXT("男");
	int age = 20;
	CString dep = TEXT("ABC");
	strsql.Format(TEXT("insert into student values('%s','%s','%s',%d,'%s')"), id, name, sex, age, dep);
	pRecordset = pMyConnect->Execute(_bstr_t(strsql), NULL, adCmdText);

在这里插入图片描述

删除

	//删除
	strsql = TEXT("delete from student where sname='测试'");
	pRecordset = pMyConnect->Execute(_bstr_t(strsql), NULL, adCmdText);

CString的格式化

Format()
常用的格式字符

表示 含义
%s 字符串,例如TEXT(“Hello!”)
%d 整数,int
%ld 长整数,long
%f 单精度浮点数,float
%lf 双精度浮点数,double

更加详细的内容可以阅读以下几位博主的文章
参考文章1
参考文章2
参考文章3

猜你喜欢

转载自blog.csdn.net/weixin_44611096/article/details/106426816