📄 ch15.htm
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"><HTML><HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html;CHARSET=iso-8859-1"><SCRIPT LANGUAGE="JavaScript"><!--function popUp(pPage) { var fullURL = document.location; var textURL = fullURL.toString(); var URLlen = textURL.length; var lenMinusPage = textURL.lastIndexOf("/"); lenMinusPage += 1; var fullPath = textURL.substring(0,lenMinusPage); popUpWin = window.open('','popWin','resizable=yes,scrollbars=no,width=525,height=394'); figDoc= popUpWin.document; zhtm= '<HTML><HEAD><TITLE>' + pPage + '</TITLE>'; zhtm += '</head>'; zhtm += '<BODY bgcolor="#FFFFFF">'; zhtm += '<IMG SRC="' + fullPath + pPage + '">'; zhtm += '<P><B>' + pPage + '</B>'; zhtm += '</BODY></HTML>'; window.popUpWin.document.write(zhtm); window.popUpWin.document.close(); // Johnny Jackson 4/28/98 }//--> </SCRIPT><link rel="stylesheet" href="/includes/stylesheets/ebooks.css"> <META NAME="GENERATOR" Content="Symantec Visual Page Mac 1.1.1"> <TITLE>Teach Yourself Visual C++ 6 in 21 Days -- Ch 15 -- Updating and Adding Database Records Through ADO</TITLE></HEAD><BODY TEXT="#000000" BGCOLOR="#FFFFFF"><H1 ALIGN="CENTER"><IMG SRC="../button/sams.gif" WIDTH="171" HEIGHT="66" ALIGN="BOTTOM"BORDER="0"><BR>Teach Yourself Visual C++ 6 in 21 Days</H1><CENTER><P><A HREF="../ch14/ch14.htm"><IMG SRC="../button/previous.gif" WIDTH="128" HEIGHT="28"ALIGN="BOTTOM" ALT="Previous chapter" BORDER="0"></A><A HREF="../ch16/ch16.htm"><IMGSRC="../button/next.gif" WIDTH="128" HEIGHT="28" ALIGN="BOTTOM" ALT="Next chapter"BORDER="0"></A><A HREF="../index.htm"><IMG SRC="../button/contents.gif" WIDTH="128"HEIGHT="28" ALIGN="BOTTOM" ALT="Contents" BORDER="0"></A> <HR></CENTER><H1 ALIGN="CENTER">- 15 -<BR>Updating and Adding Database Records Through ADO</H1><H1></H1><UL> <LI><A HREF="#Heading1">What Is ADO?</A> <UL> <LI><A HREF="#Heading2">ADO Objects</A> <LI><A HREF="#Heading3">Using the ADO ActiveX Control</A> <LI><A HREF="#Heading4">Importing the ADO DLL</A> <LI><A HREF="#Heading5">Connecting to a Database</A> <LI><A HREF="#Heading6">Executing Commands and Retrieving Data</A> <LI><A HREF="#Heading7">_CommandPtr pCmd;</A> <LI><A HREF="#Heading8">Navigating the Recordset</A> <LI><A HREF="#Heading9">Accessing Field Values</A> <LI><A HREF="#Heading10">Updating Records</A> <LI><A HREF="#Heading11">Adding and Deleting</A> <LI><A HREF="#Heading12">Closing the Recordset and Connection Objects</A> </UL> <LI><A HREF="#Heading13">Building a Database Application Using ADO</A> <UL> <LI><A HREF="#Heading14">Creating the Application Shell</A> <LI><A HREF="#Heading15">Building a Custom Record Class</A> <LI><A HREF="#Heading16">3:</A> <LI><A HREF="#Heading17">Connecting and Retrieving Data</A> <LI><A HREF="#Heading18">Populating the Form</A> <LI><A HREF="#Heading19">Saving Updates</A> <LI><A HREF="#Heading20">Navigating the Record Set</A> <LI><A HREF="#Heading21">Adding New Records</A> <LI><A HREF="#Heading22">Deleting Records</A> </UL> <LI><A HREF="#Heading23">Summary</A> <LI><A HREF="#Heading24">Q&A</A> <LI><A HREF="#Heading25">Workshop</A> <UL> <LI><A HREF="#Heading26">Quiz</A> <LI><A HREF="#Heading27">Exercise</A> </UL></UL><P><HR SIZE="4"><BR>Now that you've gotten your feet wet with an ODBC database application, one of theoldest Microsoft database access technologies, it's time to turn your attention tothe newest Microsoft database access technology, ActiveX Data Objects (ADO). Designedfor use with all of Microsoft's programming and scripting technologies, ADO presentsthe Visual C++ programmer with new challenges in database programming, while stillkeeping the functionality familiar. Today, you will learn</P><P><UL> <LI>How ADO works and how it uses the OLE DB technology for providing simple database access. <P> <LI>How you can build a simple ADO application in a couple of minutes using ActiveX controls. <P> <LI>How you can build a complete database application using regular forms controls. <P> <LI>How you can use special ADO macros to build a custom record set class for use in your database applications.</UL><BLOCKQUOTE> <P><HR><STRONG>CAUTION:</STRONG> This chapter works with some features that may not be included in all versions of Visual C++. Although ADO is an important new area of pro-gramming with Microsoft data access technologies, this chapter discusses some things that you may not have the ability to do with your version of Visual C++.<HR></BLOCKQUOTE><H2><A NAME="Heading1"></A>What Is ADO?</H2><P>A couple years ago, Microsoft designed a new data access technology called OLEDB. This data access technology was intended to be much more than simply a way ofgetting data into and out of databases. This technology was intended to be the meansof accessing data, regardless of where that data may be located. Through the OLEDB technology, you could access mail messages, spreadsheets, files, and so on. Anythingthat might have data could possibly be accessed through the OLE DB technology. Thiswas one of the first technologies to be produced from the research and developmentof the object- oriented file system at the heart of what Microsoft has been calling"Cairo" for the past few years.</P><BLOCKQUOTE> <P><HR><STRONG>NOTE:</STRONG> Many of the technologies bundled under the product name of Cairo will be released some time next year in the Windows NT 5.0 operating system.<HR></BLOCKQUOTE><P>As you can imagine, with the range of functionality that OLE DB must have to accessdata in all of those different sources, it might be quite complex to work with thistechnology. Well, it is. This is where ActiveX Data Objects come into play. ADO wasdesigned as another layer on top of OLE DB, specifically for providing database access.</P><P>One of the goals in designing ADO was to create a control that could be used toprovide data access and control in Web pages, caching the data records on the client.Part of the reason for this goal was to allow a Web browser user to access an entireset of data records, without having to pull down each individual record, one at atime, to navigate and make changes to the records. Because of this capability withADO, the ADO control is distributed with Microsoft's Internet Explorer Web browser(version 4.0 and above).</P><P><H3><A NAME="Heading2"></A>ADO Objects</H3><P>To make ADO as easily usable in scripting languages such as VBScript as it isin programming environments such as Visual Basic, Microsoft tried to keep the numberof objects to a minimum. As a result, you have a small number of basic objects:</P><P><UL> <LI>Connection <P> <LI>Error <P> <LI>Command <P> <LI>Parameter <P> <LI>Recordset <P> <LI>Field</UL><P>Along with these objects, you have collection objects for containing collectionsof Error, Parameter, and Field objects.</P><P><H4>The Connection Object</H4><P>The Connection object is used for establishing and maintaining a connection toa database. This object is configured with the connection information, includingdatabase location, user ID, and password, before opening the connection. Once allof this information is appropriately configured, the connection object should haveits Open method called to open the connection. Once the Connection object goes outof scope, the connection is automatically closed. If you want more control over closingand opening the database connection, you can call the Connection object's Close methodto close the connection.</P><P>The Connection object is also the object through which any high-level connectionfunctionality is controlled. This includes all transaction control, through the Connectionobject's BeginTrans, CommitTrans, and RollbackTrans methods.</P><P><H4>The Error Object</H4><P>Whenever a database error occurs, the error information from the database is placedinto an ADO Error object. The error information in the error object is the databaseerror information, not ADO error information. Whenever you encounter an error andneed to look up the error information to determine what went wrong, you'll need toexamine the database error codes and descriptions, not the ADO error codes.</P><P><H4>The Command Object</H4><P>The Command object is used to execute commands in the database. You can use thisobject to run SQL statements or call stored procedures (SQL functions that are storedin the database). Any time that a command returns rows of data, you need to attachthe Command object to a Recordset object for the returned data to be stored in.</P><P>When you call a stored procedure, as with functions in any other programming language,you'll often need to pass parameters to the stored procedure. To pass these parameters,you'll attach a series of Parameter objects to the Command object. Each of the Parameterobjects will have the name of the parameter that it holds the value for, along withthe value that should be passed to the database for that particular parameter.</P><P><H4>The Parameter Object</H4><P>The Parameter object is used for passing variables and for calling stored proceduresor parameterized queries. These are attached to a Command object for use in callingthe command that has been programmed into the Command object.</P><P><H4>The Recordset Object</H4><P>The Recordset object contains a set of records from the database. The set of recordsis the result of a command being sent to the database that results in a set of recordsbeing returned. You can navigate through the Recordset, much like you do with theRecordset objects for other database access technologies. You can also access thefields in each record in the Recordset through the Field objects that are associatedwith the Recordset. You can update the records in the Recordset, and then use theRecordset to update the database. You can also insert new records into the Recordset,or delete records and have those changes made in the database.</P><P><H4>The Field Object</H4><P>The Field object represents a single column in the Recordset. Each Field objectcontains the column name, data value, and how the data value should be represented.Because ADO was designed to be used in Microsoft's scripting languages, and the onlydata type available in these scripting languages is the Variant data type, the Fieldobjects always contain a Variant data value. The data value is automatically convertedto the correct data type when updating to the database. As the programmer workingwith the ADO objects, you will have to convert the value from a Variant to whateverdata type you need it to be, as well as convert it back to a Variant when updatingthe value.</P><P><H3><A NAME="Heading3"></A>Using the ADO ActiveX Control</H3><P>There are two different ways in which you can use the ADO control in your VisualC++ applications. The simple way to incorporate ADO into your application is throughthe use of ActiveX controls. You can add the ADO data control to your Visual C++project, just like any other ActiveX control, as shown in Figure 15.1.</P><P><A HREF="javascript:popUp('15fig01.gif')"><B>FIGURE 15.1.</B></A><B> </B><I>Addingthe ADO ActiveX control to a project.</I></P><P>Once you add the ADO control to your project, and place it on a window, you'llneed to specify the data connection in the control properties, as shown in Figure15.2. You'll also need to specify the source for the records that will be retrievedby the control, as shown in Figure 15.3.</P><P><A HREF="javascript:popUp('15fig02.gif')"><B>FIGURE 15.2.</B></A><B> </B><I>Specifyingthe database connection.</I></P><P><A HREF="javascript:popUp('15fig03.gif')"><B>FIGURE 15.3.</B></A><B> </B><I>Specifyingthe record source.</I></P><P>To use the ADO control efficiently, you'll also want to use data-bound controlsthat are ADO-enabled, such as the Microsoft DataGrid control. When you add thesecontrols to the window with the ADO control, you'll specify the ADO control as thedata source for the control, as shown in Figure 15.4. If the control is designedto only provide access to a single field in a record set, you'll also need to specifywhich field is to be used for the control.</P><P><A HREF="javascript:popUp('15fig04.gif')"><B>FIGURE 15.4.</B></A><B> </B><I>Specifyingthe data source.</I></P><P>Once you add all these controls to the window and configure them, you can runyour application and have full database access through ADO without having writtena single line of code, as shown in Figure 15.5.</P><P><A HREF="javascript:popUp('15fig05.gif')"><B>FIGURE 15.5.</B></A><B> </B><I>Arunning ADO control database application.</I></P><P>This is such a simple way to build database applications: Just place controlson a window and configure the properties to tell it where to get the data. What'sthe downside of building ADO applications this way? First, using this approach involvesa lot of unnecessary overhead in building ADO applications. For each SQL query ortable that you want to pull in a separate record set, you have to add a separateADO control. Each of these ADO controls will establish a separate connection to thedatabase, which could cause problems with databases that have a limited number ofconnections available (not to mention the additional overhead on the application).Finally, not all data-bound controls are ADO enabled. ADO is such a new technologythat there are few controls that you can use with it at this time. You may find somecontrols that allow you to retrieve and display data for the user, but do not allowthe user to change and edit the data. Others may not even provide you with that muchfunctionality.</P><P><H3><A NAME="Heading4"></A>Importing the ADO DLL</H3><P>If you look around in the MFC class hierarchy, you'll find that there are no classes
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -