用ADO类操ACCESS作数据库的介质损耗监控软件

 


 用regsvr32.exe打开msado15.dll,这可以进行msado动态链接库的注册。
在VC环境下导入动态链接库:
1.在StdAfx.h文件中,加入:
// 加入ADO支持库, jingzhou xu
#import "D:\EN\cv\VC6CN\SHARED\ADO\msado15.dll"  no_namespace  rename("EOF","adoEOF") 
将EOF指着定义成adoEOF
2.在对话框类中建立ado类提供的3个外部接口的指针
_ConnectionPtr m_pConnection;
_RecordsetPtr m_pRecordset;
_CommandPtr m_pCommand;
这三个对象用来调用成员函数进行数据库操作
m_pConnection主要用来执行SQL命令,建立数据库链接,也可已返回一个记录集
m_pRecordset主要是用来返回一个记录集
m_pCommand主要用来执行SQL命令返回记录集
通过这三个指针执行下需要的SQL语句,然后返回记录集指针,利用指针遍历数据记录集,并作一些处理
3.建立数据库连接
	try
	{//你的ADO代码
	   HRESULT hr;
	   hr = m_pConnection.CreateInstance("ADODB.Connection");///创建Connection对象
	   if(SUCCEEDED(hr))
	   hr = m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data 							   Source=try1.mdb","","",adModeUnknown);///连接数据库
	}
	catch (_com_error& e)
	{
	   CString strMsg;strMsg.Format(_T("错误描述:%s\n错误消息%s"),(LPCTSTR)e.Description(),(LPCTSTR)e.ErrorMessage());
	   AfxMessageBox(strMsg);
	}
用m_pConnection来建立连接,try1.mdb存在工程文件者所在目录,当贞洁使用EXE以后应该放在exe目录。否侧这里要填写处全部路径。
 4.关闭数据库连接
 
	if(m_pRecordset!=NULL)		//关闭指针

              m_pRecordset->Close();

         m_pConnection->Close();		//关闭链接
5.查询记录集
	CString aa;
	aa.Format("SELECT * FROM %s", bb);

	m_Grid.DeleteAllItems;//先将列表控件中所有项目清除

	if(m_pConnection==NULL)	
		MessageBox("请先链接数据库");    //判断可能未链接数据库
	else
	{
		//打开某一个记录集
		try
		{//你的ADO代码
			//m_pRecordset.CreateInstance(__uuidof(Recordset));		//这两句用来创建Recordset对象的实例
			m_pRecordset.CreateInstance("ADODB.Recordset");			//
			m_pRecordset->Open((_variant_t)aa, m_pConnection.GetInterfacePtr(), 
				adOpenDynamic,  adLockOptimistic, adCmdText);		//代开记录集,其中可使用SQL语句

			if(!m_pRecordset->BOF)									//指针不为空,表中有数据
				m_pRecordset->MoveFirst();
			else  
			{    
				AfxMessageBox("数据为空");
				return; 
			}

		}
		catch (_com_error& e)
		{
			CString strMsg;strMsg.Format(_T("错误描述:%s\n错误消息%s"), (LPCTSTR)e.Description(),  (LPCTSTR)								e.ErrorMessage());
			AfxMessageBox(strMsg);
		}
		//遍历并显示记录中的每一条内容
		try
		{
			int i=0;
			while(!m_pRecordset->adoEOF)		 //遍历结果集中的内容,显示在列表控件中 

			{				
			  m_Grid.InsertItem(i,"");			//插入一个新的行

			  m_Grid.SetItemText(i,0,(char*)(_bstr_t)m_pRecordset->GetCollect("序列号"));

			  m_Grid.SetItemText(i,1,(char*)(_bstr_t)m_pRecordset->GetCollect("日期"));

			  m_Grid.SetItemText(i,2,(char*)(_bstr_t)m_pRecordset->GetCollect("时间"));

			  m_Grid.SetItemText(i,3,(char*)(_bstr_t)m_pRecordset->GetCollect("采样值"));

			  //将记录集指针移动到下一条记录
			  i++;
			  m_pRecordset->MoveNext();

			}

		}
		catch (_com_error& e)
		{
		  CString strMsg;strMsg.Format(_T("错误描述:%s\n错误消息%s"), (LPCTSTR)e.Description(),(LPCTSTR)				  e.ErrorMessage());
		  AfxMessageBox(strMsg);
		}
	}
m_pRecordset指针来执行命令并返回记录集,SQL命令是主要是利用字符串CString拼接的方式。命令执行后返回指向记录集的指针存在m_pRecordset指针变量。
想要得到不同的返回记录和主要通过改变对应的SQL语句来是实现。
 
6.插入一条记录咋,在当前表中ID最大值的后面插入。
首先利用SQL语句得到一个返回按降序排列的ID字段记录,读取第一条记录味道最大值。
	if(SUCCEEDED(m_pRecordset->State))
	  m_pRecordset->Close();		///如果已经打开记录,关闭记录集

		
	aa.Format("select * FROM  %s order by 序列号 desc", st);   //当前表st,当前序列号由Index给出
//	MessageBox(aa);

	m_pRecordset->Open((_variant_t)aa, m_pConnection.GetInterfacePtr(), 
	  adOpenDynamic,  adLockOptimistic, adCmdText);
	if(m_pRecordset->adoEOF)
	{
	  bb="0";
	}
	else
	{
	  bb = (char*)(_bstr_t)m_pRecordset->GetCollect("序列号");				
	}
还是利用字符串拼接技术。然后再当前表中添加新的记录

try
 {
   if(SUCCEEDED(m_pRecordset->State))
     m_pRecordset->Close();    ///如果已经打开记录,关闭记录集

   aa.Format("SELECT * FROM  %s ", st);   //当前表st,当前序列号由Index给出

   m_pRecordset->Open((_variant_t)aa, m_pConnection.GetInterfacePtr(), 
    adOpenDynamic,  adLockOptimistic, adCmdText);
  

   haoma=atol(bb);
   bb.Format("%ld",haoma+1);
//  MessageBox(bb);

   CTime t = CTime::GetCurrentTime(); //获取日期
   CString str=t.Format("%Y/%m/%d");  //转换成CString  
//  MessageBox(str);
   CString str1=t.Format("%X");  //转换成CString

    
   //在进行更新以前也应该表中所有记录打开
   m_pRecordset->AddNew(); //添加操作   
   m_pRecordset->PutCollect(_variant_t("序列号"), _variant_t(bb)); //添加表的元素   
   m_pRecordset->PutCollect(_variant_t("日期"), _variant_t(str)); //添加表的元素 
   m_pRecordset->PutCollect(_variant_t("时间"), _variant_t(str1)); //添加表的元素
   m_pRecordset->PutCollect(_variant_t("采样值"),_variant_t(m_nowJiesun) ); //添加表的元素 
   m_pRecordset->Update(); //执行更新,成功插入  
}  
 catch (_com_error& e)
 {
  CString strMsg;strMsg.Format(_T("错误描述:%s\n错误消息%s"), (LPCTSTR)e.Description(),(LPCTSTR)e.ErrorMessage());
  AfxMessageBox(strMsg);
 }

使用m_pRecordset对象的PutCollect成员函数,其函数原型是:m_Ado.m_pRecordset->PutCollect("编号",(_bstr_t)m_ID);

7.删除一条记录

CString a;
 a.Format("SELECT * FROM %s WHERE 序列号=%s", st,xuliehao); //先用SQL语句查询到指定记录,然后执行下面的删除操作   try
{                                                                                                                                     m_pRecordset->Open((_variant_t)a,  m_pConnection.GetInterfacePtr(),                             			adOpenDynamic,adLockOptimistic,adCmdText);        //获得要删除的内容   
  if(!m_pRecordset->adoEOF)   {  
   m_pRecordset->MoveFirst();//用来定位   
   m_pRecordset->Delete(adAffectCurrent);//根据位置删除   						                        //注:这里根据自己的需要进行操作,如果有多个结果,则要循环获得下标进行删除   
  }  
}
catch (_com_error& e)
{
  CString strMsg;strMsg.Format(_T("错误描述:%s\n错误消息%s"), (LPCTSTR)e.Description(),(LPCTSTR)e.ErrorMessage());
  AfxMessageBox(strMsg);
}

8.新建表

try  
{  
  CString aaa;
  aaa.Format("CREATE TABLE %s (序列号 Long, 日期 date, 时间 time, 采样值 Double)", edx.m_NewTable);
  MessageBox(aaa);
  m_pRecordset.CreateInstance(__uuidof(Recordset));  
  m_pRecordset->Open((_variant_t)aaa,  
  m_pConnection.GetInterfacePtr(),  
	adOpenDynamic,adLockOptimistic,adCmdText);//获得想要修改的内容   

}  
catch (_com_error& e)
{
  CString strMsg;strMsg.Format(_T("错误描述:%s\n错误消息%s"), (LPCTSTR)e.Description(),(LPCTSTR)e.ErrorMessage());
  AfxMessageBox(strMsg);
} 

9.删除表,显得到表名,在领用SQL语句删除,使用DROP TABLE 语句,再删除表之前先要将表关闭。

if(SUCCEEDED(m_pRecordset->State))
  m_pRecordset->Close();				///如果已经打开记录,关闭记录集                                                     try  
{  
  CString aaaa;
  aaaa.Format("DROP TABLE %s",st);   //拼接字符串
					 
  _variant_t RecordsAffected;
	m_pConnection->Execute(_bstr_t(aaaa),&RecordsAffected,adCmdText);  
  }  
catch (_com_error& e)
{
  CString strMsg;strMsg.Format(_T("错误描述:%s\n错误消息%s"), (LPCTSTR)e.Description(),(LPCTSTR)e.ErrorMessage());
  AfxMessageBox(strMsg);
} 	
 

10.给对话框加背景图片

void CJiesunxinxiDlg::OnPaint() {  if (IsIconic())  {   CPaintDC dc(this); // device context for painting

  SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

  // Center icon in client rectangle   int cxIcon = GetSystemMetrics(SM_CXICON);   int cyIcon = GetSystemMetrics(SM_CYICON);   CRect rect;   GetClientRect(&rect);   int x = (rect.Width() - cxIcon + 1) / 2;   int y = (rect.Height() - cyIcon + 1) / 2;

  // Draw the icon   dc.DrawIcon(x, y, m_hIcon);  }  else  { //  CDialog::OnPaint();    CPaintDC   dc(this);       CRect   rect;       GetClientRect(&rect);       CDC   dcMem;       dcMem.CreateCompatibleDC(&dc);       CBitmap   bmpBackground;       bmpBackground.LoadBitmap(IDB_LANSE);   //IDB_LANSE是你自己的图对应的ID   ,由于我刚刚加入的位图资源                      BITMAP   bitmap;       bmpBackground.GetBitmap(&bitmap);       CBitmap   *pbmpOld=dcMem.SelectObject(&bmpBackground);       dc.StretchBlt(0,0,rect.Width(),rect.Height(),&dcMem,0,0,       bitmap.bmWidth,bitmap.bmHeight,SRCCOPY);    } }

11.设置静态文本灰色背景为透明(在对话框的WM_ctrCOLOR消息添加响应函数)

HBRUSH CJiesunxinxiDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) 
{
   HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
   HBRUSH m_hBkBrush   =   (HBRUSH)::GetStockObject(NULL_BRUSH);   //创建一个空画刷,使控件背景透明  
	
   // TODO: Change any attributes of the DC here
   switch(nCtlColor)

   {
      case CTLCOLOR_STATIC: //对所有静态文本控件的设置
       {
	pDC->SetBkMode(TRANSPARENT);//设置背景为透明 
           pDC->SetTextColor(RGB(0,0,0)); //设置字体颜色
	return HBRUSH(GetStockObject(HOLLOW_BRUSH)); // 必须
       }
      case CTLCOLOR_DLG: //对所有静态文本控件的设置
       {
	pDC->SetBkMode(TRANSPARENT);  
         return hbr; //返回画刷句柄
       }
      case CTLCOLOR_BTN:
      {
	pDC->SetBkMode(TRANSPARENT);  
	return   (HBRUSH)   m_hBkBrush;  
      }
      default:
      return CDialog::OnCtlColor(pDC,pWnd, nCtlColor);
  }
  // TODO: Return a different brush if the default is not desired
  return hbr;
}

12.替换程序图标

直接在RESOURCE中替换调ico,删掉在插入同样ID的ICO运行即可

*******************************************************************************

串口通信MSCOM

1.先注册mscomm32.ocx

2.在对话框中加入Microsoft Communications Control, version 6.0控件(电话)

3.设置控件ID:IDC_MSCOMM1,在ClassWizard->Member Viariables中为IDC_MSCOMM1添加变量m_ctrlComm(运行一下看是否报错)

4.加入两个EDIT分别作为接受和发送。为他们关联变量:一般使用CString,便于显示各种字符串包括浮点数。m_Receive和m_Send

5.在ClassWizard->Message Maps中为IDC_MSCOMM1控件添加OnComm()响应事件。添加代码,读取缓冲区的数据

void CJiesunxinxiDlg::OnOnCommMscomm1() 
{
   // TODO: Add your control notification handler code here
    CString strTemp,str;
    float jiesun=0;
    unsigned char temp;
    static unsigned char dealflag=0,count=0;

    VARIANT variant_inp;
    COleSafeArray safearray_inp;  //收接发送时候缓冲区中是VARIANT类型 而edit里面应该是从cstring
    LONG len,k;
    BYTE rxdata[2048]; //设置BYTE数组 An 8-bit integerthat is not signed.
    CString strtemp;
    if(m_ctrMSCom.GetCommEvent()==2) //事件值为2表示接收缓冲区内有字符
    {             以下你可以根据自己的通信协议加入处理代码
        variant_inp=m_ctrMSCom.GetInput(); //读缓冲区
        safearray_inp=variant_inp; //VARIANT型变量转换为ColeSafeArray型变量
        len=safearray_inp.GetOneDimSize(); //得到有效数据长度
        for(k=0;k<len;k++)
            safearray_inp.GetElement(&k,rxdata+k);//转换为BYTE型数组
    }
}

接着添加一帧数据的处理代码

for ( k=0;k<len;k++)      //将数组转换为CString型变量
{
   //这里添加数据处理代码
}

6.添加串口初始化代码

void CJiesunxinxiDlg::inticom()
{
  if(m_ctrMSCom.GetPortOpen())
  _ctrMSCom.SetPortOpen(FALSE);

  m_ctrMSCom.SetCommPort(comIndex);
  //每次对combobox进行选择之后都会进入处理函数对
  //comIndex进行赋值,可以直接对全局变量conIndex进行引用
   m_ctrMSCom.SetSettings ( "9600,N,8,1");
  //设置了串行口的波特率,校验位,数据位数,停止位  这里是字符串形式,可以利用字符拼接来实现各种参数
  //m_ctrMSCom.SetSettings (baudrate);
  if( !m_ctrMSCom.GetPortOpen())
    m_ctrMSCom.SetPortOpen(TRUE);//打开串口
  else
    AfxMessageBox("cannot open serial port");
  //以下设置只有当串口有效的时候设置才有效
  m_ctrMSCom.SetInputMode(1); 
  //1:表示以二进制方式检取数据
  m_ctrMSCom.SetInputLen(0); 
  //设置接收区数据长度,0表示接收全部
  m_ctrMSCom.SetRThreshold(1); 
  //参数1表示每当串口接收缓冲区中有多于或等于1个字符时将引发一个接收数据的OnComm事件
  m_ctrMSCom.GetInput();
  //先预读缓冲区以清除残留数据
}

7.combox串口号选择

void CJiesunxinxiDlg::OnSelendokComnum() 
{
  // TODO: Add your control notification handler code her
  CString sting;
  comIndex=1;   //COMBOX索引从0开始
  comIndex+=m_ctrCom.GetCurSel();
  sting.Format("%d ",comIndex);
  m_Receive+=sting;  //在接收框中显示选择的com号码
  m_comIndex=comIndex-1; 
  UpdateData(FALSE);		
}


最后得到下面效果:



 

 


 


 
 

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值