Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 112 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
112
Dung lượng
3,36 MB
Nội dung
Chapter 25 Working With Database Objects In Code If you need an immediate solution to: A Full-Scale DAO Example Using The Daocode Example To Create And Edit A Database DAO: Creating A Database DAO: Creating A Table With A TableDef Object DAO: Adding Fields To A TableDef Object DAO: Adding An Index To A TableDef Object DAO: Creating A Record Set DAO: Opening A Database DAO: Adding A Record To A Record Set DAO: Editing A Record In A Record Set DAO: Updating A Record In A Record Set DAO: Moving To The First Record In A Record Set DAO: Moving To The Last Record In A Record Set DAO: Moving To The Next Record In A Record Set DAO: Moving To The Previous Record In A Record Set DAO: Deleting A Record In A Record Set DAO: Sorting A Record Set DAO: Searching A Record Set DAO: Executing SQL A Full-Scale RDO Example RDO: Opening A Connection RDO: Creating A Result Set RDO: Moving To The First Record In A Result Set RDO: Moving To The Last Record In A Result Set RDO: Moving To The Next Record In A Result Set RDO: Moving To The Previous Record In A Result Set RDO: Executing SQL A Full-Scale ADO Example ADO: Opening A Connection ADO: Creating A Record Set From A Connection ADO: Binding Controls To Record Sets ADO: Adding A Record To A Record Set Visual Basic 6 Black Book:Working With Database Objects In Code http://24.19.55.56:8080/temp/ch25\851-854.html (1 of 3) [3/14/2001 2:05:23 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ADO: Refreshing The Record Set ADO: Updating A Record In A Record Set ADO: Moving To The First Record In A Record Set ADO: Moving To The Last Record In A Record Set ADO: Moving To The Next Record In A Record Set ADO: Moving To The Previous Record In A Record Set ADO: Deleting A Record In A Record Set ADO: Executing SQL In A Record Set In Depth Programming database objects is an enormously complex topic that in itself can take up a dozen volumes. There is a career’s worth of work here, so we’ll have our hands full in this chapter. Here, we’re going to perform many of the tasks we first saw in the previous chapter, but while we used the data, remote data, and ADO data controls in that chapter, we’ll execute those tasks in code directly in this chapter, using the Visual Basic data object libraries. Working with the data object libraries provides more flexibility, more power—and a great deal more complexity. DAO We’ll use Data Access Object (DAO) methods to do what we did in the beginning of the last chapter: build a database and allow users to move through that database, editing it as they like. To construct a database, we’ll create it, create a table with fields and add it to that database, and also construct an index for the database that will let us sort it. Working with DAO, you can use the Database and Recordset Data Access Objects in your procedures. The Database and Recordset objects each have properties and methods of their own, and you can write procedures that use these properties and methods to manipulate your data. TIP: Note that in the Learning Edition of Visual Basic, you can’t declare (with the Dim keyword) variables as Data Access Objects in code. This means that only the data control can create Database and Recordset objects, not your code. To open a database in DAO, you just open a Database object or create a new one. This object can represent a Microsoft Jet database (.mdb) file, an ISAM database (for example, Paradox), or an ODBC database connected through the Microsoft Jet database engine. When the Database object is available, you create a Recordset object and use that object’s methods, like MoveFirst and MoveNext, to work with the database. DAO also supports a client/server connection mode called ODBCDirect. ODBCDirect establishes a connection directly to an ODBC data source, without loading the Microsoft Jet database engine into memory, and is a good solution when you need ODBC features in your program. In the ODBCDirect object model, the Connection object contains information about a connection to an ODBC data source, such as the server name, the data source name, and so on. It is similar to a Database Visual Basic 6 Black Book:Working With Database Objects In Code http://24.19.55.56:8080/temp/ch25\851-854.html (2 of 3) [3/14/2001 2:05:23 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com object; in fact, a Connection object and a Database object represent different references to the same object. (In this chapter, we’ll stick with the Database/Recordset model.) RDO With the Remote Data Objects (RDO) library of data objects, you establish an rdoConnection to an ODBC data source, then create an rdoResultset (please note, it is not an rdoRecordset). The Remote Data Objects behave like the DAO objects in many ways, because there is a core set of methods that work with both record sets and result sets. The big difference between DAO and RDO objects is that the RDO objects are largely SQL-driven. For example, although you can move through a database using methods like MoveNext and MoveLast, just as you would with the DAO objects, programmers often update and modify RDO data sources using SQL statements directly with the rdoConnection object’s Execute method. (In this book, we’ll stick to what you can do with Visual Basic.) Visual Basic 6 Black Book:Working With Database Objects In Code http://24.19.55.56:8080/temp/ch25\851-854.html (3 of 3) [3/14/2001 2:05:23 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ADO As we saw in the last chapter, ActiveX Data Objects (ADO) access data from OLE DB providers. The Connection object is used to specify a particular provider and any parameters. To connect to a data source, you use a Connection object. Using that connection, you can create a new record set, and using the Recordset object’s methods and properties, you can work with your data. An ADO transaction marks the beginning and end of a series of data operations that are executed across a connection. ADO makes sure that changes to a data source resulting from operations in a transaction either all occur successfully, or not at all. If you cancel the transaction or one of its operations fails, then the result will be as if none of the operations in the transaction had occurred. In this chapter, we’ll see how to create connections using the ADO Connection object and how to open data providers, creating an ADO Recordset object. We’ll read data from the data provider and see how to display and modify it. In fact, we’ll see how to support data-bound controls directly in code. Although the ADO model is a complex one, and OLE DB is even more complex, we’ll see that many of the core ADO Resultset methods are the same as the DAO Resultset methods. TIP: Note that in DAO and ADO you work with record sets, and in RDO with result sets; it’s very easy to confuse the terminology here. That’s it, then, for the overview of databases. We’ve seen how the process works in overview; now it’s time to turn to the Immediate Solutions. Immediate Solutions A Full-Scale DAO Example To illustrate DAO data handling in code, we’ll build a fully functional DAO project—the daocode project. This program has a File menu with the following items: • New Database—Creates a new database. • Open Database—Opens a database. • Close Database—Closes the current database. • New Table—Creates a new table. • Search—Searches the database. • Sort—Sorts the database. • Exit—Exits the application. Using The Daocode Example To Create And Edit A Database To create a database file, select the New Database menu item. Next, add a table to that database with the New Table menu item, then add records to that table. When you’re ready to store the database on disk, use the Close Database item. Visual Basic 6 Black Book:Working With Database Objects In Code http://24.19.55.56:8080/temp/ch25\854-857.html (1 of 2) [3/14/2001 2:05:25 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com WARNING! If you don’t create a table in a database before trying to add data to a table in that database with the Add or Edit buttons, the daocode program generates an error. In addition, the program has buttons that let users add, edit, update, and delete records, as well as letting them move through a database, as shown in Figure 25.1. Each time you want to add a record (including when you enter the first record of a new database), click the Add New Record button, type in the data for the record’s fields, and click the Update Database button to update the database. Figure 25.1 Our DAO database-building application, the daocode project. To edit a record, open the record, click the Edit button, edit the data in the record’s fields, and click the Update Database button to update the database. For simplicity, this program only creates tables with two fields, although you can place as many records as you like in each table. We’ll develop the code for this example program in the next several topics of this chapter. For reference, the main form of this example program is located in the daocode folder on this book’s accompanying CD-ROM; the form the user uses to specify the names of the fields in a new table is located in the TableForm folder on CD-ROM; and the code for the form in which the user can enter a text string to search for is located in the SearchForm folder on the CD-ROM. Visual Basic 6 Black Book:Working With Database Objects In Code http://24.19.55.56:8080/temp/ch25\854-857.html (2 of 2) [3/14/2001 2:05:25 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com DAO: Creating A Database The Testing Department is calling again. How about creating a DAO database—in code? Hmm, you think, is that possible? It is, with the objects in the Microsoft DAO Object Library. To add a reference to that library, select the Project|References menu item, select the Microsoft DAO Object Library, and click on OK to close the References dialog box. Now we can make use of the data objects in that library to create a new database using CreateDatabase. CreateDatabase is a method of the DAO Workspace object (there are a collection of Workspace objects in the DAO DBEngine object’s Workspaces collection). Here’s how you use CreateDatabase: Set database = workspace.CreateDatabase (name, locale [, options]) Here are the arguments to CreateDatabase: • name—A string up to 255 characters long that is the name of the database file that you’re creating. It can be the full path and file name, such as C:vbbb\db.mdb. If you don’t supply a file name extension, .mdb is added. • locale—A string that specifies a collating order for creating the database, like dbLangGeneral (which includes English), dbLangGreek, and so on. TIP: You can create a password for a new Database object by concatenating the password (starting with “;pwd=”) with a constant in the locale argument, like this: dbLangGreek & “;pwd=NewPassword”. If you want to use the default locale, but specify a password, simply enter a password string for the locale argument: “;pwd=NewPassword”. Here are the possible settings for the options argument: • dbEncrypt—Creates an encrypted database. • dbVersion10—Creates a database that uses the Jet engine version 1 file format. • dbVersion11—Creates a database that uses the Jet database engine version 1.1 file format. • dbVersion20—Creates a database that uses the Jet database engine version 2 file format. • dbVersion30—The default. Creates a database that uses the Jet database engine version 3 file format (compatible with version 3.5). Let’s see an example to make this clearer. When the user selects the New database item in our example DAO program, daocode (see the first topic in this chapter), we will create a new database. First, we declare that database, db, as a form-wide variable: Dim db As Database Next, we add a Common Dialog control, CommonDialog1, to the program and show it to get the name of the database file the user wants to create: Private Sub NewDatabase_Click() CommonDialog1.ShowSave Visual Basic 6 Black Book:Working With Database Objects In Code http://24.19.55.56:8080/temp/ch25\857-859.html (1 of 3) [3/14/2001 2:05:32 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com If CommonDialog1.FileName <> "" Then Finally, we create the new database, passing the CreateDatabase method the name of the database file and indicating that we want to use the default collating order by passing the constant dbLangGeneral: Private Sub NewDatabase_Click() CommonDialog1.ShowSave If CommonDialog1.FileName <> "" Then Set db = DBEngine.Workspaces(0).CreateDatabase_ (CommonDialog1.FileName, dbLangGeneral) End If End Sub And that’s it—we’ve created a new, empty database. The next step is to add a table to that database, and we’ll take a look at that in the next topic. DAO: Creating A Table With A TableDef Object How do you create a table in a DAO database? You define it with a TableDef object. After you do so, you can append fields to the table, and then you can append the new table definition to a database’s TableDefs collection. Let’s see an example. After the users create a new database with our DAO code example, the daocode project (see the first topic in this chapter), they can create a new table using the New Table item in the File menu. That item opens the New Table dialog box you see in Figure 25.2. Figure 25.2 The New Table dialog box. Users can enter the name of the new table to create in the text boxes in the New Table dialog box, and we can use that information to create a new TableDef object, td, which we declare as a form-wide variable: Dim td As TableDef We create a new TableDef for the Database object we created in the previous topic, db, using the name for the table the user has placed in Text1 in the New Table dialog box: Sub CreateTable() Set td = db.CreateTableDef(TableForm.Text1.Text) This code creates a new, empty TableDef object named td. An empty table isn’t much use, though—we’ll see about adding fields to this object in the next topic. Visual Basic 6 Black Book:Working With Database Objects In Code http://24.19.55.56:8080/temp/ch25\857-859.html (2 of 3) [3/14/2001 2:05:32 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Visual Basic 6 Black Book:Working With Database Objects In Code http://24.19.55.56:8080/temp/ch25\857-859.html (3 of 3) [3/14/2001 2:05:32 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com DAO: Adding Fields To A TableDef Object How do you add fields to a DAO TableDef object? You can use that object’s CreateField method to do that, passing that method the name of the new field and a constant indicating that field’s type: TableDef.CreateField( FieldName, FieldType) Here are the constants specifying the possible field types: • dbBigInt • dbBinary • dbBoolean • dbByte • dbChar • dbCurrency • dbDate • dbDecimal • dbDouble • dbFloat • dbGUID • dbInteger • dbLong • dbLongBinary (OLE object) • dbMemo • dbNumeric • dbSingle • dbText • dbTime • dbTimeStamp • dbVarBinary Let’s see an example to make this clearer. In the previous topic, we created a TableDef object named td for the daocode example project (see the first topic in this chapter), and now we can add two fields to that object, which we declare in an array named fields of type Field (which is defined in the DAO library): Dim fields(2) As Field The users have specified what names they want to give to those two new fields in the New Table dialog box’s text boxes, so we create the new fields this way: Sub CreateTable() Visual Basic 6 Black Book:Working With Database Objects In Code http://24.19.55.56:8080/temp/ch25\859-863.html (1 of 3) [3/14/2001 2:05:36 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Set td = db.CreateTableDef(TableForm.Text1.Text) Set fields(0) = td.CreateField(TableForm.Text2.Text, dbText) Set fields(1) = td.CreateField(TableForm.Text3.Text, dbText) Now that the new fields are created, we can append them to the actual TableDef object td: Sub CreateTable() Set td = db.CreateTableDef(TableForm.Text1.Text) Set fields(0) = td.CreateField(TableForm.Text2.Text, dbText) Set fields(1) = td.CreateField(TableForm.Text3.Text, dbText) td.fields.Append fields(0) td.fields.Append fields(1) End Sub That’s it—we’ve defined two new fields, named them, and appended them to a TableDef object. Next, we’ll add an index to our table to allow the user to sort the data in that object. DAO: Adding An Index To A TableDef Object You use an index to sort a table, and you create an index with the DAO CreateIndex method. The CreateIndex method creates an Index object, and you can make one of the fields in a table that table’s index with that Index object’s CreateField method. Let’s see an example to make this clearer. We’ll create an index for our DAO example, the daocode project (see the first topic in this chapter) named dbindex, which we declare as a form-wide variable: Dim dbindex As Index We name the index when we create it; here, we’ll just use the first field that the user has placed in this table as the table’s index so all sort operations will sort using that field. In this example, we name our index by adding the word “index” to the name of that field this way: Sub CreateTable() Set td = db.CreateTableDef(TableForm.Text1.Text) Set fields(0) = td.CreateField(TableForm.Text2.Text, dbText) Set fields(1) = td.CreateField(TableForm.Text3.Text, dbText) td.fields.Append fields(0) td.fields.Append fields(1) Set dbindex = td.CreateIndex(TableForm.Text2.Text & "index") Visual Basic 6 Black Book:Working With Database Objects In Code http://24.19.55.56:8080/temp/ch25\859-863.html (2 of 3) [3/14/2001 2:05:36 AM] Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... in the adocode folder on this book s accompanying CD-ROM http://24.19.55. 56: 80 80/temp/ch25 \87 9 -88 4.html (4 of 5) [3/14/2001 2: 06: 04 AM] Visual Basic 6 Black Book: Working With Database Objects In Code Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com http://24.19.55. 56: 80 80/temp/ch25 \87 9 -88 4.html (5 of 5) [3/14/2001 2: 06: 04 AM] Visual Basic 6 Black Book: Working With Database Objects... some of the data in that result set http://24.19.55. 56: 80 80/temp/ch25 \8 76- 87 9.html (3 of 4) [3/14/2001 2:05:57 AM] Visual Basic 6 Black Book: Working With Database Objects In Code Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com http://24.19.55. 56: 80 80/temp/ch25 \8 76- 87 9.html (4 of 4) [3/14/2001 2:05:57 AM] Visual Basic 6 Black Book: Working With Database Objects In Code RDO: Moving... http://24.19.55. 56: 80 80/temp/ch25\ 86 3 - 86 5 .html (2 of 3) [3/14/2001 2:05: 38 AM] Visual Basic 6 Black Book: Working With Database Objects In Code Besides creating a new database as we’ve done, however, the user may want to open an existing database, Simpo PDF Merge and the Unregistered and we’ll see how to do that inSplit next topic Version - http://www.simpopdf.com http://24.19.55. 56: 80 80/temp/ch25\ 86 3 - 86 5 .html... method: http://24.19.55. 56: 80 80/temp/ch25\ 86 5 - 86 9 .html (3 of 4) [3/14/2001 2:05:41 AM] Visual Basic 6 Black Book: Working With Database Objects In Code Private Sub Command3_Click() Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com dbrecordset.fields(0) = Text1.Text dbrecordset.fields(1) = Text2.Text dbrecordset.Update End Sub http://24.19.55. 56: 80 80/temp/ch25\ 86 5 - 86 9 .html (4 of 4) [3/14/2001... (ODBCDirect workspaces only) • dbExecDirect—Runs a query by skipping SQLPrepare and directly calling SQLExecDirect (ODBCDirect workspaces only) http://24.19.55. 56: 80 80/temp/ch25\ 86 3 - 86 5 .html (1 of 3) [3/14/2001 2:05: 38 AM] Visual Basic 6 Black Book: Working With Database Objects In Code • dbInconsistent—Allows inconsistent updates (Microsoft Jet dynaset-type and snapshot-type Recordset objects only).Split... or the file name of a Recordset • ActiveConnection—A valid Connection object variable name or a string containing ConnectionString parameters http://24.19.55. 56: 80 80/temp/ch25 \88 4 -88 7.html (1 of 3) [3/14/2001 2: 06: 09 AM] Visual Basic 6 Black Book: Working With Database Objects In Code • Type—Sets the Recordset type (see the following list) •Simpo PDF Merge and Split Unregistered Version - locking (concurrency)... in the students table this way when the form loads, using the Open method: Private Sub Form_Load() Dim db As Connection Set db = New Connection http://24.19.55. 56: 80 80/temp/ch25 \88 4 -88 7.html (2 of 3) [3/14/2001 2: 06: 09 AM] Visual Basic 6 Black Book: Working With Database Objects In Code db.Open "PROVIDER=Microsoft.Jet.OLEDB.3.51;Data _ Source=C:\vbbb\adocode\db.mdb;" Simpo PDF Merge and Split Unregistered... code for the rdocode project in the following few topics For reference, the code for this example is located in the rdocode folder on this book s accompanying CD-ROM http://24.19.55. 56: 80 80/temp/ch25 \87 4 -8 76. html (2 of 2) [3/14/2001 2:05:51 AM] Visual Basic 6 Black Book: Working With Database Objects In Code RDO: Opening A Connection Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com... As Integer CommonDialog1.ShowOpen If CommonDialog1.FileName "" Then Set db = _ DBEngine.Workspaces(0).OpenDatabase(CommonDialog1.FileName) http://24.19.55. 56: 80 80/temp/ch25\ 86 5 - 86 9 .html (1 of 4) [3/14/2001 2:05:41 AM] Visual Basic 6 Black Book: Working With Database Objects In Code table1index = 0 While (db.TableDefs(table1index).Attributes And Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com... earlier in this chapter), when the user clicks the appropriate button: Private Sub cmdLast_Click() On Error GoTo ErrLabel resultset.MoveLast http://24.19.55. 56: 80 80/temp/ch25 \87 9 -88 4.html (1 of 5) [3/14/2001 2: 06: 04 AM] Visual Basic 6 Black Book: Working With Database Objects In Code Exit Sub Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ErrLabel: MsgBox Err.Description End . method. (In this book, we’ll stick to what you can do with Visual Basic. ) Visual Basic 6 Black Book: Working With Database Objects In Code http://24.19.55. 56: 80 80/temp/ch25 85 1 -85 4.html (3 of 3). SQLExecDirect (ODBCDirect workspaces only). Visual Basic 6 Black Book: Working With Database Objects In Code http://24.19.55. 56: 80 80/temp/ch25 86 3 - 86 5 .html (1 of 3) [3/14/2001 2:05: 38 AM] Simpo PDF Merge and Split. later topics in this chapter. Visual Basic 6 Black Book: Working With Database Objects In Code http://24.19.55. 56: 80 80/temp/ch25 86 3 - 86 5 .html (2 of 3) [3/14/2001 2:05: 38 AM] Simpo PDF Merge and Split