ODBC 与 Access
这是一篇关于本人使用ODBC 具体步骤(Visual C++6.0 +Access 2000)
动态创建数据源,数据库(默认test.mdb),表及其查询,插入,修改,删除。
一般说来ODBC数据库的使用分为以下几步是:
创建数据库对象-> 连接数据库-> 创建记录集-> 打开记录集-> 操作记录集- > 关闭和销毁记录集-> 关闭和销毁数据库对象。
下面就具体步骤介绍:
1.打开Visual C++6.0(并确定安装了Access 2000),为了简便我们就新建一个基于对话框的工程(Dialog),
新建->工程->MFC AppWizard(exe)->在工程名处输入:DyODBC(工程名称)->选基于对话框->其它默认点完成即可
2.在FileView选项卡的Header Files文件夹中
(1)打开DyODBCDlg.h加入代码:
#include
#pragma comment(lib,"odbccp32.lib") //为了使用ODBC API的函数 SQLConfigDataSource
(2)打开StdAfx.h加入代码:
#include //以提供对CDatabase 类的支持
3.在ResourceView选项卡的Dialog文件夹中
点击标记为IDD_DYODBC_DIALOG来编辑对话框界面,为对话框加入如下控件(先删除:TODO: 在这里设置对话控制。):
6个按钮控件
ID Caption
IDC_CREATEDSN 创建数据源
IDC_CREATEDATABASE 创建数据库
IDC_CREATETABLE 创建表
IDC_DELETEDSN 删除数据源
IDC_DELETEDATABASE 删除数据库
IDC_DELETETABLE 删除表
IDC_SHOWDATAINFO 显示数据表
加入显示对话框:选ResourceView 的 DyODBC resources 目录下Dialog点右键Insert Dialog,选IDD_DIALOG1右键Properties将ID改为:IDD_SHOWDATADLG然后加入如下控件:
1个列表控件
ID Styles
IDC_LISTCONTROL View:Report
为对话框加一个类,在对话框上点击右键->ClassWizard->CLassWizard再弹出的的对话框(Adding a Class)选Create a new class (默认选项,这是提示我们为刚才第二个对话框加一个新类),点确定,在弹出的New Class对话框中填写类名为:ShowDataDlg,其他默认即可,点确定;
为列表控件绑定变量,在列表控件点击右键双击后在弹出的对话框 Member variable name:输入m_showlist 其它默认,点确定;
4.为控件加入相应的代码
(1)双击按钮“创建数据源”在弹出的对话框(Add Member Function)默认名OnCreatedsn,点确定即可;
// TODO: Add your control notification handler code here
//在此处加入如下代码:
CString strPath=GetCurrentPath();//得到应用程序的路径
CString strDSN;
strDSN.Format("%s",dsnName);
// strDSN.Format("%s%s%s",dsnName,strPath,mdbName);
if(SQLConfigDataSource(NULL,ODBC_ADD_SYS_DSN,sDriver,strDSN))//创建数据源
MessageBox("Create DSN is OK!!","Create",MB_OK);
else
MessageBox("Create DSN isn't OK!!","Create",MB_OK);
(2)双击按钮“创建数据库”在弹出的对话框(Add Member Function)默认名OnCreatedatabase,点确定即可
// TODO: Add your control notification handler code here
//在此处加入如下代码:
CString strPath=GetCurrentPath();
CString strMDB="CREATE_DB="+strPath+mdbName;
MessageBox(strMDB,"!!!",MB_OK);
if(SQLConfigDataSource(NULL,ODBC_ADD_SYS_DSN,sDriver,strMDB))
MessageBox("Create Database is OK!!","Create",MB_OK);
else
MessageBox("Create Database isn't OK,May be test.mdb is exist!!","Create",MB_OK);
(3)双击按钮“创建表”在弹出的对话框(Add Member Function)默认名OnCreatetable,点确定即可
// TODO: Add your control notification handler code here
//在此处加入如下代码:
CString strSQLexe[]={
_T("Create table test(iID int , tmJoin datetime, szName varchar(40),fTall float );"),
_T("create table student(sno varchar(10) , sname varchar(12), age int);"),
_T("insert into student(sno,sname,age) values('jkx0013001','xkl',22);"),
_T("Insert into test values(1111, '2002-1-3 13:25' , 'user_3',1.76 );"),
_T("Insert into test values(2222, '2002-1-1 15:25' , 'user_1',1.56 );"),
_T("Insert into test values(3333, '2002-1-2 12:25' , 'user_2',1.53 );"),
_T("Insert into test values(4444, '2002-1-3 13:25' , 'user_3',1.76 );"),
};
TRY
{
CString strPath=GetCurrentPath();
pDb.OpenEx(dsnName+strPath+mdbName);//,CDatabase::openReadOnly);//打开
if(!pDb.IsOpen())//判断是否打开
MessageBox("Open Database is Failed!!!","Create",MB_OK);
else
{
pDb.ExecuteSQL(strSQLexe[0]);
pDb.ExecuteSQL(strSQLexe[1]);
pDb.ExecuteSQL(strSQLexe[2]);
pDb.ExecuteSQL(strSQLexe[3]);
pDb.ExecuteSQL(strSQLexe[4]);
pDb.ExecuteSQL(strSQLexe[5]);
pDb.ExecuteSQL(strSQLexe[6]);
}
}
CATCH(CDBException, e)
{ // The error code is in e->m_nRetCode
pDb.Close();
CString strTip=_T("Database operate Fail! ");
strTip+=_T("Because: ")+e->m_strError;
AfxMessageBox(strTip);
}
END_CATCH
pDb.Close();
(4)双击按钮“删除数据源”在弹出的对话框(Add Member Function)默认名OnDeletedsn,点确定即可
// TODO: Add your control notification handler code here
//在此处加入如下代码:
if(SQLConfigDataSource(NULL,ODBC_REMOVE_SYS_DSN,sDriver,dsnName))
MessageBox("Delete DSN is OK!!","Delete",MB_OK);
else
MessageBox("Delete DSN isn't OK,May be the DSN isn't exist!!","Delete",MB_OK);
(5)双击按钮“删除数据库”在弹出的对话框(Add Member Function)默认名OnDeletedatebase,点确定即可
// TODO: Add your control notification handler code here
//在此处加入如下代码:
if(DeleteFile(GetCurrentPath()+mdbName))
MessageBox("Delete Database Success!","Delete",MB_OK);
else
MessageBox("Delete Database Fail!","Delete",MB_OK);
(6)双击按钮“删除表”在弹出的对话框(Add Member Function)默认名OnDeletetable,点确定即可
// TODO: Add your control notification handler code here
//在此处加入如下代码:
TRY
{
CString strPath=GetCurrentPath();
pDb.OpenEx(dsnName+strPath+mdbName);//,CDatabase::openReadOnly);//打开
if(!pDb.IsOpen())//判断是否打开
{ MessageBox("Open Database is Failed!!!","Create",MB_OK);
}
else
{
pDb.ExecuteSQL("delete table from test;"); //delete table
pDb.ExecuteSQL("delete from student"); //delete table
pDb.Close();
}
}
CATCH(CDBException, e)
{ // The error code is in e->m_nRetCode
pDb.Close();
CString strTip=_T("Database operate Fail! ");
strTip+=_T("Because: ")+e->m_strError;
AfxMessageBox(strTip);
}
END_CATCH
pDb.Close();
(7)双击按钮“显示数据表”在弹出的对话框(Add Member Function)默认名OnShowdatainfo,点确定即可
// TODO: Add your control notification handler code here
//在此处加入如下代码:
ShowDataDlg dlg;
dlg.DoModal ();
(8)在DyODBCDlg.cpp文件开始处加入
#include "globals.h" //自定义的变量
#include "ShowDataDlg.h"
5.为ShowDataDlg 添加显示功能,
(1)在ShowDataDlg.cpp文件开始处
#include "DyODBCDlg.h"
extern CDatabase pDb;
extern CString dsnName;
extern CString mdbName;
(2)在ClassView处选ShowDataDlg点右键选Add Window Message Handler...项,在弹出的对话框,New Windows messages/events:栏中找到WM_INITDIALOG双击后,点Add Handler 按扭,加入如下代码:
// TODO: Add extra initialization here
// 对记录集的操作
CRecordset* dbset=new CRecordset(&pDb);//
CDyODBCDlg dlg;
CString strPath=dlg.GetCurrentPath ();//Get application path
TRY
{
pDb.OpenEx(dsnName+strPath+mdbName,CDatabase::noOdbcDialog);//打开
if(!pDb.IsOpen ())
AfxMessageBox("Open dsnName Error.");//m_databaseinfo);
else
{
CString strSQL=_T("select * from test");
// CString strSQL=_T("select * from student");
// CString strSQL=_T("select sname from student where age=33;");
// CString strSQL=_T("select iid, tmjoin from test where iid=1111;");
dbset->Open(CRecordset::dynaset,strSQL,CRecordset::readOnly);
//统计table信息
short FieldCount=dbset->GetODBCFieldCount ();
do { dbset->MoveNext(); } while (!dbset->IsEOF());
long RecordCount=dbset->GetRecordCount();
CString title[MAX_PATH]={""};
CODBCFieldInfo fieldinfo;
CStringArray strColTitle;
if(!dbset->IsBOF()) dbset->MoveFirst();
if(strColTitle.GetSize()) strColTitle.RemoveAll();
//显示列标题(字段名)
for(int i=0;i {
dbset->GetODBCFieldInfo(i,fieldinfo);
strColTitle.Add(LPCTSTR(fieldinfo.m_strName));
m_showlist.InsertColumn (i,strColTitle[i]);//title[i]);
}
CString item[MAX_PATH];
CString strField;
//显示记录
dbset->MoveFirst();
for(i=0;i {
m_showlist.InsertItem (i,"");
for(int j=0;j {
dbset->GetFieldValue (j,strField);
m_showlist.SetItemText (i,j,strField);
m_showlist.SetColumnWidth (j,LVSCW_AUTOSIZE);
}
dbset->MoveNext ();
}
dbset->Close ();
delete dbset;
pDb.Close();
}
}
CATCH(CDBException, e)
{ // The error code is in e->m_nRetCode
dbset->Close ();
delete dbset;
pDb.Close();
CString strTip=_T("Database operate Fail! ");
strTip+=_T("Because: ")+e->m_strError;
AfxMessageBox(strTip);
}
END_CATCH
6.为工程加入全局变量,点新建 -> 文件 里C/C++ Header File 名为:globals.h
CDatabase pDb;
CString dsnName=_T("DSN=演示数据源;DBQ="); //数据源
CString sDriver=_T("Microsoft Access Driver (*.mdb)"); //驱动
CString mdbName=_T("test.mdb"); //数据库名
7.为DyODBCDlg.cpp加入成员函数GetCurrentPath(),
在ClassView 选中CDyODBCDlg点右键,选Add Member Function...;在弹出的对话框中对应如下:
Function Type: CString
Function Declaration: GetCurrentPath()
Access : Public
点确定后加入以下代码:
//取得当前的工作路径
CString sPath;
CString strDBFile;
GetModuleFileName(NULL,sPath.GetBufferSetLength (MAX_PATH+1),MAX_PATH);
sPath.ReleaseBuffer();
int nPos=sPath.ReverseFind ('');
sPath=sPath.Left(nPos);
strDBFile = sPath;
return _T(strDBFile);
8.连接,运行。。。
//这是我的学习的笔记,有什么不对之处,请与我联系
//感谢你的浏览(完)