Home Database Mysql Tutorial MFC中简单的数据库文件操作(添加,修改,查找,删除)

MFC中简单的数据库文件操作(添加,修改,查找,删除)

Jun 07, 2016 pm 02:59 PM
mfc Revise delete operate database document Find Add to Simple want

要求:新建一个数据库文件(微软的 access ) , 里面包括学生的信息学号( ID ),姓名( Name ) , 英语成绩( English ) , 在 Visual C 6.0 里新建 MFC 项目,新建学生记录类( StudentRecordSet ) , 与数据库文件绑定。在 C 里面对文件里的信息进行添加

要求:新建一个数据库文件(微软的access,里面包括学生的信息学号(ID),姓名(Name,英语成绩(English,Visual C++ 6.0里新建MFC项目,新建学生记录类(StudentRecordSet,与数据库文件绑定。在C++里面对文件里的信息进行添加,查找,输出,删除操作。

1.       首先新建一个MFC项目,这里取名为data

 2.        在项目文件里,新建一个微软的access文件,取名为source

 

MFC中简单的数据库文件操作(添加,修改,查找,删除)

3.    打开source.mdb文件,点击使用设计器创建表,在表中字段名称 向下依次输入ID  Name  English ,前两个数据类型为文本,后一个数据类型为数字。选中ID的那一行,右键,设为主键(唯一的设为主键,比如一个班里的学生,每个人都有一个学号,各不相同,是唯一的)。关闭时提示是否保存对表1的修改,点击是,另存为 表名称 source 确定。

MFC中简单的数据库文件操作(添加,修改,查找,删除)

 

4.要把该数据文件设置为数据源。具体方法为打开电脑的控制面板,在里面找到管理工具,再找到数据源,双击打开,点击添加,选择Driver do Microsoft Access(* .mdb),在弹出的对话框中数据源名  source  ,数据库选择那里选择上面我们建立的数据库文件(source.mdb.

MFC中简单的数据库文件操作(添加,修改,查找,删除)

5.接下来对MFC项目进行操作。在类视图data classes右键,new class(添加类),Type  MFC Class.     Name: StudentRecordSet   Base class: CRecordset   OK。在弹出的对话框里ODBC选择source ,RecordsetType 选择Dynaset动态,OK,这样  StudentRecordSet类就和数据库文件绑定了。

MFC中简单的数据库文件操作(添加,修改,查找,删除)

     点击鼠标左键向 source.mdb 数据库文件中存数据。

1.CDataView右键添加消息句柄,选择OnLButtonDown,进入函数void CDataView::OnLButtonDown(UINT nFlags, CPoint point)中,在里面写入下面代码:

       StudentRecordSet rs; //建立对象

       rs.Open();   //打开数据库文件

       rs.AddNew();  //添加新数据

       rs.m_ID="001";  //第一条记录的ID

       rs.m_Name="Tom";

       rs.m_English=100;

       rs.Update(); //更新

       rs.Close(); //关闭文件

编译运行有错误。1class StudentRecordSet : public CRecordset 基类CRecordset不认识,双击StudentRecordSet类,添加头文件#include 2.View类中用到了StudentRecordSet rs; //建立对象 ,类StudentRecordSet不认识,双击CDataView,加入头文件,#include “StudentRecordSet.h”,编译成功。

MFC中简单的数据库文件操作(添加,修改,查找,删除)

MFC中简单的数据库文件操作(添加,修改,查找,删除)

2.运行,点击鼠标左键,界面无任何反应,实际上rs.m_ID="001"; rs.m_Name="Tom";rs.m_English=100;数据已经存储到文件source.mdb中了,打开文件,看看,已经添加进去了。

MFC中简单的数据库文件操作(添加,修改,查找,删除)

如果继续在刚才的运行窗口点击鼠标左键,出现错误。是因为又向文件中添加一条相同的记录,但是已经设 ID为主键了,唯一,不能重复添加。

MFC中简单的数据库文件操作(添加,修改,查找,删除)

3.     如果再向文件中添加一条新纪录,需要修改如下代码的值

StudentRecordSet rs; //建立对象

       rs.Open();   //打开数据库文件

       rs.AddNew();  //添加新数据

       rs.m_ID="001";  //第一条记录的ID     修改001

       rs.m_Name="Tom";                      修改Tom

       rs.m_English=100;                       修改100

       rs.Update(); //更新

       rs.Close(); //关闭文件

这里我把 001改为002    Tom改为 Jerry  100改为99,编译运行,鼠标左键,OK,到数据库文件 source.mdb中看一看,新纪录已经被添加了。PS:添加新纪录,也可以在文件中直接添加,不用再C++里面。

MFC中简单的数据库文件操作(添加,修改,查找,删除)

MFC中简单的数据库文件操作(添加,修改,查找,删除)

②点击鼠标右键,将数据库中的信息显示出来。

1.CDataView类右键添加消息句柄,选择OnRButtonDown,进入void CDataView::OnRButtonDown(UINT nFlags, CPoint point),添加下面代码:

       StudentRecordSet rs; //建立对象

       rs.Open();

       int y=20;  //控制y坐标的变化,换行

       CString strTemp;//临时变量

       CClientDC dc(this);//客户区

       while(!rs.IsEOF())  //判断是否到文件尾

       {

              strTemp.Format("ID:%s , Name:%s , English:%d",rs.m_ID,rs.m_Name,rs.m_English);//格式化

              dc.TextOut(20,y,strTemp);//dc调用函数textout显示出内容

              rs.MoveNext(); //指针默认在第一条记录,用这句话使指针下移

              y+=20;//换行

       }

       rs.Close();

MFC中简单的数据库文件操作(添加,修改,查找,删除)

OK,编译,运行,点击鼠标右键,数据库中的内容全部显示在面板上。(不要再点击鼠标左键,否则会出现上面提到的相同的错误,鼠标左键里的代码可以先注释掉)

MFC中简单的数据库文件操作(添加,修改,查找,删除)

③修改内容以及指定内容修改

1.修改内容是对第一条记录修改的,在鼠标左键里的函数里写下面代码:

                            rs.Close(); //关闭文件*/

                      StudentRecordSet rs;

                      rs.Open();

                      rs.Edit();

                      rs.m_English=60;

                      rs.Update();

                      rs.Close();

编译运行,先点击左键,再点击右键,发现第一条记录的英语成绩已经被修改成了60

MFC中简单的数据库文件操作(添加,修改,查找,删除)

MFC中简单的数据库文件操作(添加,修改,查找,删除)

2.指定内容修改把刚才加的代码注释掉,加入以下代码:

                   StudentRecordSet rs;

                   rs.m_strFilter="ID='002'";  //ID为主键,唯一,信息过滤,ID002的那一条记录,对它进行修改

                   rs.Open();

                   rs.Edit();

                   rs.m_English=80;//修改英语成绩

                   rs.Update();

                   rs.Close();

编译,运行,左键,右键,发现ID002的英语成绩已经被修改为了 80

MFC中简单的数据库文件操作(添加,修改,查找,删除)

 

MFC中简单的数据库文件操作(添加,修改,查找,删除)

④内容的查找

还是在鼠标左键的函数里,把刚才 修改 的代码注释掉,写下面代码:

                   StudentRecordSet rs;

                   rs.m_strFilter="English=80";   //这里的意思是 要查找英语成绩为80的所有记录

                   rs.Open();

                   CClientDC dc(this);

                   CString strTemp;

                   int y=20;

                   while(!rs.IsEOF())

                   {

                     strTemp.Format("ID:%s,Name:%s,English:%d",rs.m_ID,rs.m_Name,rs.m_English);

                     dc.TextOut(20,y,strTemp); //加入了显示功能,点击左键

                     rs.MoveNext();

                     y+=20; //换行

                   }

                   rs.Close();

OK,编译,运行,点击鼠标左键,发现英语成绩为80的记录被显示。因为数据库文件中只有两条记录,有一条记录英语的成绩为80,所以这里只显示一条记录。PS(查找不能加 rs.Update()函数,这个函数只跟在加入记录和修改记录后面);

MFC中简单的数据库文件操作(添加,修改,查找,删除)

 

 

 MFC中简单的数据库文件操作(添加,修改,查找,删除)

⑤内容的删除

这里指定内容删除就不说了,和指定内容修改差不多,把rs.Edit();换成rs.Delete();

下面是全部内容删除。

方法一:

1.把鼠标左键函数里刚才写的代码注释掉,加入下面代码:

                   StudentRecordSet rs;

                   rs.Open();

                   while(!rs.IsEOF())

                   {

                     rs.Delete();  //删除记录

                     rs.MoveNext();

                   }

                   rs.Close();

OK,编译,运行。左键。查看数据库文件.access

如下:

MFC中简单的数据库文件操作(添加,修改,查找,删除)

所有数据被删除。(这种方法,效率低,编程来删除文件数据,下面方法二是让数据库文件source.mdb来删除数据,效率高)

方法二:

1.把刚才方法一的代码注释掉。

加入以下代码:

CDatabase db;

                   StudentRecordSet rs(&db);

                   CString strSql="delete from source";

                   rs.Open();

                   db.ExecuteSQL(strSql);

                   rs.Close();

编译,运行,左键单击。OK达到与方法1同样的效果,文件里的数据全部删除

MFC中简单的数据库文件操作(添加,修改,查找,删除)

 

附上左键函数的代码:

void CDataView::OnLButtonDown(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default

/*	StudentRecordSet rs; //建立对象
	rs.Open();   //打开数据库文件
	rs.AddNew();  //添加新数据
	rs.m_ID="002";  //第一条记录的ID值
	rs.m_Name="Jerry";
	rs.m_English=99;
	rs.Update(); //更新
	rs.Close(); //关闭文件*/

/*	StudentRecordSet rs;
	rs.Open();
	rs.Edit();
	rs.m_English=60;
	rs.Update();
	rs.Close();*/  //修改内容

	/*StudentRecordSet rs;
	rs.m_strFilter="ID='002'";
	rs.Open();
	rs.Edit();
	rs.m_English=80;
	rs.Update();
	rs.Close();*/  //指定内容修改

	/*StudentRecordSet rs;
	rs.m_strFilter="English=80";
	rs.Open();
	CClientDC dc(this);
	CString strTemp;
	int y=20;
	while(!rs.IsEOF())
	{
		strTemp.Format("ID:%s , Name:%s , English:%d",rs.m_ID,rs.m_Name,rs.m_English);
		dc.TextOut(20,y,strTemp);
		rs.MoveNext();
		y+=20;
	}
	rs.Close();*/    //查找并显示


	/*StudentRecordSet rs;
	rs.Open();
	while(!rs.IsEOF())
	{
		rs.Delete();
		rs.MoveNext();
	}
	rs.Close();*/ //删除方法1

	CDatabase db;
	StudentRecordSet rs(&db);
	CString strSql="delete from source";
	rs.Open();
	db.ExecuteSQL(strSql);
	rs.Close(); //删除方法2
	CView::OnLButtonDown(nFlags, point);
}
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
1655
14
PHP Tutorial
1255
29
C# Tutorial
1228
24
How to completely delete TikTok chat history How to completely delete TikTok chat history May 07, 2024 am 11:14 AM

1. Open the Douyin app, click [Message] at the bottom of the interface, and click the chat conversation entry that needs to be deleted. 2. Long press any chat record, click [Multiple Select], and check the chat records you want to delete. 3. Click the [Delete] button in the lower right corner and select [Confirm deletion] in the pop-up window to permanently delete these records.

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Jun 25, 2024 pm 07:09 PM

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

How to use database callback functions in Golang? How to use database callback functions in Golang? Jun 03, 2024 pm 02:20 PM

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

How to connect to remote database using Golang? How to connect to remote database using Golang? Jun 01, 2024 pm 08:31 PM

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

See all articles