Home Database Mysql Tutorial VC++对Access数据库的操作(查询、插入、更新、删除等)

VC++对Access数据库的操作(查询、插入、更新、删除等)

Jun 07, 2016 pm 03:42 PM
access delete insert operate database renew Inquire

Microsoft Office Access是由 微软 发布的 关系 数据库 管理系统 。 Access 数据库 常应用于小型软件系统中, 比如: 生产管理 、 销售管理 、 库存管理 等各类企业管理软件,其最大的优点是:简单易学、使用灵活。 下面我们结合实例来详细说明,在VC MFC中

Microsoft Office Access是由微软发布的关系数据库管理系统Access数据库常应用于小型软件系统中,比如:生产管理销售管理库存管理等各类企业管理软件,其最大的优点是:简单易学、使用灵活。

下面我们结合实例来详细说明,在VC++ MFC中,如何使用Access数据库文件进行数据的存储,如何实现对数据库中数据的查询插入更新删除操作

(实例可在我的CSDN资源中下载:http://download.csdn.net/detail/margin1988/8235865)

首先,怎样创建一个可供VC++ MFC程序使用的Access数据库,并在该数据库中创建数据表呢?

第一步:打开Microsoft Office Access软件,点击“空白数据库”;

VC++对Access数据库的操作(查询、插入、更新、删除等)

第二步:设置预创建空白数据库的文件名和文件类型(文件名:point32.mdb,文件类型:Microsoft Office Access 2000 数据库(*.mdb));

VC++对Access数据库的操作(查询、插入、更新、删除等)

第三步:“创建”空白数据库

VC++对Access数据库的操作(查询、插入、更新、删除等)

第四步:为该数据库“设置数据库密码”(本例中密码设置为:1234);

VC++对Access数据库的操作(查询、插入、更新、删除等)

第五步:在该数据库中创建一张表,例如:TestTab(编号,姓名,性别,年龄);

VC++对Access数据库的操作(查询、插入、更新、删除等)

第六步:表创建完成后,保存并关闭数据库,然后将该数据库文件(point32.mdb)剪切到你的VC++程序debug或release目录中,则准备工作完成。

其次,在VC++ MFC中编写对该数据库TestTab表进行数据查询插入更新删除操作的方法:

(1)导入才用ado方式访问Access数据库所需的DLL

1

#import "C:\Program Files\Common Files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF")//ado访问ACCESS<strong>数据库</strong>必需

Copy after login

(2)在程序的入口函数中,初始化OLE以支持应用程序

1

AfxOleInit();

Copy after login

(3)获取应用程序(EXE)所在路径

1

2

3

4

5

6

7

CString path;//应用程序所在路径

char filepath[256];

char* pPath;

GetModuleFileName(AfxGetInstanceHandle(),filepath,256);

pPath  = strrchr(filepath,'\\');

*pPath = 0;

path = filepath;

Copy after login

(4)创建数据库访问连接字符串

1

2

3

4

5

6

char* PtConnectStr;//<strong>数据库</strong>连接字符串

CString connstr =  "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";

connstr += path;

connstr += "\\point32.mdb";

connstr += ";Jet OLEDB:Database Password='1234'";

PtConnectStr = connstr.GetBuffer(0);

Copy after login

(5)查询TestTab表中数据方法实现

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

//<strong>查询</strong>表中数据,并显示在List Control控件中

void CPoint32Dlg::ReadUserInfo()

{

    //select

    m_list.DeleteAllItems();//清空列表

 

    _ConnectionPtr m_pConnection;

    _RecordsetPtr m_pRecordset;

 

    try

    {

        m_pConnection.CreateInstance(__uuidof(Connection));

        m_pConnection->Open(PtConnectStr,"","",adModeUnknown);

    }

    catch(_com_error e)

    {

        CString errormessage;

        errormessage.Format("<strong>数据库</strong>连接失败.\r错误信息:%s",e.ErrorMessage());

        //AfxMessageBox(errormessage);

        MessageBox(errormessage,"连接失败",MB_ICONEXCLAMATION);

        if(m_pConnection->State)

            m_pConnection->Close();

        return;

    }

 

    try

    {

 

        //获取数据,放在数据集中

        CString cmd;

        cmd.Format("SELECT * FROM TestTab");

 

        m_pRecordset.CreateInstance("ADODB.Recordset");

        m_pRecordset->Open(cmd.GetBuffer(),

            _variant_t((IDispatch*)m_pConnection,true),

            adOpenStatic,

            adLockOptimistic,

            adCmdText);

 

        //处理数据,并显示

        _variant_t varbuffer;

        long index = 0;//注意:必须是long类型

        int countItem = 0;

        CString str;

 

        while(!m_pRecordset->adoEOF)

        {

            index = 0;

            //读ID号

            varbuffer = m_pRecordset->GetCollect(_variant_t(index));        

            if(varbuffer.vt!=VT_NULL)

            {

                str.Format("%d",varbuffer.lVal);

                m_list.InsertItem(countItem,str.GetBuffer());

            }

            //读其它的信息

            while(index GetCollect(_variant_t(index));

                if(varbuffer.vt!=VT_NULL)

                {

                    str = (LPCTSTR)(_bstr_t)varbuffer;

                    m_list.SetItemText(countItem,index,str.GetBuffer());

                }

            }

 

            m_pRecordset->MoveNext();

            countItem++;

        }

    }

    catch(_com_error &e)

    {

        //AfxMessageBox(e.Description());

        MessageBox(e.Description(),"<strong>数据库</strong><strong>操作</strong>失败.",MB_ICONEXCLAMATION);

        if(m_pRecordset->State)

            m_pRecordset->Close();

        if(m_pConnection->State)

            m_pConnection->Close();

        return;

    }

 

    if(m_pRecordset->State)

        m_pRecordset->Close();

    if(m_pConnection->State)

        m_pConnection->Close();

}

Copy after login

(6)向TestTab表中插入数据方法实现

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

//向表中<strong>插入</strong>数据,并<strong>更新</strong>List Control控件中显示的数据

void CPoint32Dlg::OnBnClickedButton1()

{

    //insert

    _ConnectionPtr m_pConnection;

    _variant_t RecordsAffected;

    try

    {

        m_pConnection.CreateInstance(__uuidof(Connection));

        m_pConnection->Open(PtConnectStr,"","",adModeUnknown);

    }

    catch(_com_error e)

    {

        CString errormessage;

        errormessage.Format("<strong>数据库</strong>连接失败.\r错误信息:%s",e.ErrorMessage());

        MessageBox(errormessage,"       添加失败       ",MB_ICONEXCLAMATION);

        return;

    }

    try

    {

        CString strCmd="INSERT INTO TestTab(UName,UGender,UAge) VALUES('测试者','男','30')";

 

        for(int i=0;iExecute(strCmd.AllocSysString(),&RecordsAffected,adCmdText);

        }

    }

    catch(_com_error &e)

    {

        //AfxMessageBox(e.Description());

        MessageBox(e.Description(),"       添加失败       ",MB_ICONEXCLAMATION);

        if(m_pConnection->State)

            m_pConnection->Close();

        return;

    }

    if(m_pConnection->State)

        m_pConnection->Close();

    //MessageBox("添加成功!","消息");

 

    m_update.EnableWindow(TRUE);

    m_delete.EnableWindow(TRUE);

 

    ReadUserInfo();

}

Copy after login

(7)更新TestTab表中数据方法实现

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

//<strong>更新</strong>表中数据,并<strong>更新</strong>List Control控件的显示

void CPoint32Dlg::OnBnClickedButton3()

{

    // update

    _ConnectionPtr m_pConnection;

    _variant_t RecordsAffected;

    try

    {

        m_pConnection.CreateInstance(__uuidof(Connection));

        m_pConnection->Open(PtConnectStr,"","",adModeUnknown);

    }

    catch(_com_error e)

    {

        CString errormessage;

        errormessage.Format("<strong>数据库</strong>连接失败.\r错误信息:%s",e.ErrorMessage());

        MessageBox(errormessage,"       修改失败       ",MB_ICONEXCLAMATION);

        return;

    }

    try

    {

        CString strCmd="UPDATE TestTab SET [UGender]='女',[UAge]='20' WHERE [UName]='测试者'";

 

        m_pConnection->Execute(strCmd.AllocSysString(),&RecordsAffected,adCmdText);

    }

    catch(_com_error &e)

    {

        //AfxMessageBox(e.Description());

        MessageBox(e.Description(),"       修改失败       ",MB_ICONEXCLAMATION);

        if(m_pConnection->State)

            m_pConnection->Close();

        return;

    }

    if(m_pConnection->State)

        m_pConnection->Close();

    //MessageBox("修改成功!","消息");

 

    ReadUserInfo();

}

Copy after login

(8)删除TestTab表中数据及重置表中自动编号主键(key)方法现实

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

//<strong>删除</strong>表中数据、重置自动编号(从1开始),并<strong>更新</strong>List Control控件显示

void CPoint32Dlg::OnBnClickedButton4()

{

    // delete

    _ConnectionPtr m_pConnection;

    _variant_t RecordsAffected;

    try

    {

        m_pConnection.CreateInstance(__uuidof(Connection));

        m_pConnection->Open(PtConnectStr,"","",adModeUnknown);

    }

    catch(_com_error e)

    {

        CString errormessage;

        errormessage.Format("连接<strong>数据库</strong>失败!\r错误信息:%s",e.ErrorMessage());

        MessageBox(errormessage,"<strong>删除</strong>失败",MB_ICONEXCLAMATION);

        return;

    }

    try

    {

        //<strong>删除</strong>表中所有数据

        CString strCmd="DELETE FROM TestTab";

 

        m_pConnection->Execute(strCmd.AllocSysString(),&RecordsAffected,adCmdText);

 

        //重置表中自动编号ID,使其从1开始增加(必须先<strong>删除</strong>表中所有数据)

        strCmd="ALTER TABLE TestTab ALTER COLUMN ID COUNTER(1,1)";

 

        m_pConnection->Execute(strCmd.AllocSysString(),&RecordsAffected,adCmdText);

    }

    catch(_com_error &e)

    {

        //AfxMessageBox(e.Description());

        MessageBox(e.Description(),"<strong>删除</strong>失败",MB_ICONEXCLAMATION);

        if(m_pConnection->State)

            m_pConnection->Close();

        return;

    }

    if(m_pConnection->State)

        m_pConnection->Close();

    //MessageBox("<strong>删除</strong>成功!","完成");

 

    m_insert.EnableWindow(TRUE);

    m_update.EnableWindow(FALSE);

    m_delete.EnableWindow(FALSE);

 

    ReadUserInfo();

}

Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1652
14
PHP Tutorial
1250
29
C# Tutorial
1224
24
How to configure zend for apache How to configure zend for apache Apr 13, 2025 pm 12:57 PM

How to configure Zend in Apache? The steps to configure Zend Framework in an Apache Web Server are as follows: Install Zend Framework and extract it into the Web Server directory. Create a .htaccess file. Create the Zend application directory and add the index.php file. Configure the Zend application (application.ini). Restart the Apache Web server.

Oracle's Role in the Business World Oracle's Role in the Business World Apr 23, 2025 am 12:01 AM

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

MySQL vs. Other Databases: Comparing the Options MySQL vs. Other Databases: Comparing the Options Apr 15, 2025 am 12:08 AM

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

Using Dicr/Yii2-Google to integrate Google API in YII2 Using Dicr/Yii2-Google to integrate Google API in YII2 Apr 18, 2025 am 11:54 AM

VprocesserazrabotkiveB-enclosed, Мнепришлостольностьсясзадачейтерациигооглапидляпапакробоглесхетсigootrive. LEAVALLYSUMBALLANCEFRIABLANCEFAUMDOPTOMATIFICATION, ČtookazaLovnetakProsto, Kakaožidal.Posenesko

What is apache server? What is apache server for? What is apache server? What is apache server for? Apr 13, 2025 am 11:57 AM

Apache server is a powerful web server software that acts as a bridge between browsers and website servers. 1. It handles HTTP requests and returns web page content based on requests; 2. Modular design allows extended functions, such as support for SSL encryption and dynamic web pages; 3. Configuration files (such as virtual host configurations) need to be carefully set to avoid security vulnerabilities, and optimize performance parameters, such as thread count and timeout time, in order to build high-performance and secure web applications.

Nginx performance monitoring and troubleshooting tools Nginx performance monitoring and troubleshooting tools Apr 13, 2025 pm 10:00 PM

Nginx performance monitoring and troubleshooting are mainly carried out through the following steps: 1. Use nginx-V to view version information, and enable the stub_status module to monitor the number of active connections, requests and cache hit rate; 2. Use top command to monitor system resource occupation, iostat and vmstat monitor disk I/O and memory usage respectively; 3. Use tcpdump to capture packets to analyze network traffic and troubleshoot network connection problems; 4. Properly configure the number of worker processes to avoid insufficient concurrent processing capabilities or excessive process context switching overhead; 5. Correctly configure Nginx cache to avoid improper cache size settings; 6. By analyzing Nginx logs, such as using awk and grep commands or ELK

MySQL: Structured Data and Relational Databases MySQL: Structured Data and Relational Databases Apr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

How to use Debian Apache logs to improve website performance How to use Debian Apache logs to improve website performance Apr 12, 2025 pm 11:36 PM

This article will explain how to improve website performance by analyzing Apache logs under the Debian system. 1. Log Analysis Basics Apache log records the detailed information of all HTTP requests, including IP address, timestamp, request URL, HTTP method and response code. In Debian systems, these logs are usually located in the /var/log/apache2/access.log and /var/log/apache2/error.log directories. Understanding the log structure is the first step in effective analysis. 2. Log analysis tool You can use a variety of tools to analyze Apache logs: Command line tools: grep, awk, sed and other command line tools.

See all articles