2002 prentice hall. all rights reserved. 1 chapter 19 – databases, sql, and ado.net outline:...
Post on 15-Jan-2016
214 Views
Preview:
TRANSCRIPT
2002 Prentice Hall. All rights reserved.
1
Chapter 19 – Databases, SQL, and ADO.NET
Outline: 只上 19.1, 19.2, 19.3, 19.5, 19.619.1 Introduction19.2 Relational Database Model19.3 Relational Database Overview: The Books Database19.4 Structured Query Language (SQL)
19.4.1 Basic SELECT Query19.4.2 WHERE Clause19.4.3 ORDER BY Clause19.4.4 Merging Data from Multiple Tables: INNER
JOIN19.4.5 Joining Data from Tables Authors,
AuthorISBN, Titles and Publishers19.4.6 INSERT Statement19.4.7 UPDATE Statement19.4.8 DELETE Statement
19.5 ADO.NET Object Model
2002 Prentice Hall. All rights reserved.
2
Outline19.6 Programming with ADO.NET: Extracting Information from a DBMS
19.6.1 Connecting to and Querying an Access Data Source
19.6.2 Querying the Books Database19.7 Programming with ADO.NET: Modifying a DBMS19.8 Reading and Writing XML Files
2002 Prentice Hall. All rights reserved.
3
19.1 Introduction
• Database:– Integrated collection of data
– Database management system (DBMS)• Provides mechanisms for storing and organizing data in a way
that is consistent with database’s format
• Allows storage and access to database without knowledge of internal representation
– Relational Databases most popular• Use Structured Query Language to perform queries (search)
and manipulate data
• Programming languages need an interface to interact with relational databases
2002 Prentice Hall. All rights reserved.
4
19.2 Relational Database Model
• Logical representation of data:– Relationships can be considered without concern for
physical structure of data
• Composed of tables– Rows called records
– Columns called fields
– Primary key: field that contains unique data• Each record can be identified by at least one distinct value
– New sets made from queries called result sets
2002 Prentice Hall. All rights reserved.
5
19.2 Relational Database Model
Fig. 19.1 Relational database structure of an Employee table.
number name department salary location
23603 Jones 413 1100 New Jersey
24568 Kerwin 413 2000 New Jersey
34589 Larson 642 1800 Los Angeles
35761 Myers 611 1400 Orlando
47132 Neumann 413 9000 New Jersey
78321 Stephens 611 8500 Orlando
record/row
field/columnprimary key
2002 Prentice Hall. All rights reserved.
6
19.3 Relational Database Overview: Books Database
• Rule of Entity Integrity: every record must have a unique value in its primary-key field
• Compound Primary key: when a record has a unique key based on a combination of two fields
• Foreign key:– Field for which every entry has a unique value in another
table and where the field in the other table is the primary key for that table
– Rule of Referential Integrity: every foreign-key field value must appear in another table’s primary-key field
– One to many relationship: A foreign key can appear many times in its own table, but only once as primary key in another table
2002 Prentice Hall. All rights reserved.
7
19.3 Relational Database Overview: Books Database
Fig. 19.2 Result set formed by selecting Department and Location data from the Employee table.
department location
413 New Jersey
642 Los Angeles
611 Orlando
2002 Prentice Hall. All rights reserved.
8
19.3 Relational Database Overview: Books Database
Field Description authorID Author’s ID number in the database. In the Books database, this integer field is
defined as an auto-incremented field. For each new record inserted in this table, the database automatically increments the authorID value to ensure that each record has a unique authorID. This field represents the table’s primary key.
firstName Author’s first name (a string).
lastName Author’s last name (a string).
Fig. 19.3 Authors table from Books.
Fig. 19.3 Authors table from Books.
2002 Prentice Hall. All rights reserved.
9
19.3 Relational Database Overview: Books Database
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
3 Tem Nieto
4 Kate Steinbuhler
5 Sean Santry
6 Ted Lin
7 Praveen Sadhu
8 David McPhie
9 Cheryl Yaeger
10 Marina Zlatkina
11 Ben Wiedermann
12 Jonathan Liperi
Fig. 19.4 Data from the Authors table of Books.
Fig. 19.4 Data from the Authors table of Books.
2002 Prentice Hall. All rights reserved.
10
19.3 Relational Database Overview: Books Database
Field Description publisherID The publisher’s ID number in the database. This auto-incremented integer
is the table’s primary-key field.
publisherName The name of the publisher (a string).
Fig. 19.5 Publishers table from Books.
Fig. 19.5 Publishers table from Books.
publisherID publisherName
1 Prentice Hall
2 Prentice Hall PTG
Fig. 19.6 Data from the Publishers table of Books.
Fig. 19.6 Data from the Publishers table of Books.
2002 Prentice Hall. All rights reserved.
11
19.3 Relational Database Overview: Books Database
Field Description authorID The author’s ID number, which allows the database to associate each
book with a specific author. The integer ID number in this field must also appear in the Authors table.
isbn The ISBN number for a book (a string).
Fig. 19.7 AuthorISBN table from Books.
Fig. 19.7 AuthorISBN table from Books.
2002 Prentice Hall. All rights reserved.
12
19.3 Relational Database Overview: Books Database
authorID isbn authorID isbn
1 0130895725 2 0139163050
1 0132261197 2 013028419x
1 0130895717 2 0130161438
1 0135289106 2 0130856118
1 0139163050 2 0130125075
1 013028419x 2 0138993947
1 0130161438 2 0130852473
1 0130856118 2 0130829277
1 0130125075 2 0134569555
1 0138993947 2 0130829293
1 0130852473 2 0130284173
1 0130829277 2 0130284181
1 0134569555 2 0130895601
1 0130829293 3 013028419x
1 0130284173 3 0130161438
1 0130284181 3 0130856118
1 0130895601 3 0134569555
2 0130895725 3 0130829293
2 0132261197 3 0130284173
2 0130895717 3 0130284181
2 0135289106 4 0130895601
Fig. 19.8 Portion of data from table AuthorISBN in database Books.
Fig. 19.8 Portion of data from table AuthorISBN in database Books.
2002 Prentice Hall. All rights reserved.
13
19.3 Relational Database Overview: Books Database
Field Description isbn ISBN number of the book (a string).
title Title of the book (a string).
editionNumber Edition number of the book (an integer).
copyright Copyright year of the book (a string).
publisherID Publisher’s ID number (an integer). This value must correspond to an ID number in the Publishers table.
imageFile Name of the file containing the book’s cover image (a string).
price Suggested retail price of the book (a real number). [Note: The prices shown in this book are for example purposes only.]
Fig. 19.9 Titles table from Books.
Fig. 19.9 Titles table from Books.
2002 Prentice Hall. All rights reserved.
14
19.3 Relational Database Overview: Books Database
isbn title edition-Number
publish-erID
copy-right
imageFile
price
0130923613
Python How to Program
1 1 2002 python.jpg
$69.95
0130622214
C# How to Program
1 1 2002 cshtp.jpg
$69.95
0130341517
Java How to Program
4 1 2002 jhtp4.jpg
$69.95
0130649341
The Complete Java Training Course
4 2 2002 javactc4.jpg
$109.95
0130895601
Advanced Java 2 Platform How to Program
1 1 2002 advjhtp1.jpg
$69.95
0130308978
Internet and World Wide Web How to Program
2 1 2002 iw3htp2.jpg
$69.95
0130293636
Visual Basic .NET How to Program
2 1 2002 vbnet.jpg
$69.95
0130895636
The Complete C++ Training Course
3 2 2001 cppctc3.jpg
$109.95
0130895512
The Complete e-Business & e-Commerce Programming Training Course
1 2 2001 ebecctc.jpg
$109.95
Fig. 19.10 Data from the Titles table of Books.
2002 Prentice Hall. All rights reserved.
15
19.3 Relational Database Overview: Books Database
013089561X
The Complete Internet & World Wide Web Programming Training Course
2 2 2001 iw3ctc2.jpg
$109.95
0130895547
The Complete Perl Training Course
1 2 2001 perl.jpg $109.95
0130895563
The Complete XML Programming Training Course
1 2 2001 xmlctc.jpg
$109.95
0130895725
C How to Program
3 1 2001 chtp3.jpg
$69.95
0130895717
C++ How to Program
3 1 2001 cpphtp3.jpg
$69.95
013028419X
e-Business and e-Commerce How to Program
1 1 2001 ebechtp1.jpg
$69.95
0130622265
Wireless Internet and Mobile Business How to Program
1 1 2001 wireless.jpg
$69.95
0130284181
Perl How to Program
1 1 2001 perlhtp1.jpg
$69.95
0130284173
XML How to Program
1 1 2001 xmlhtp1.jpg
$69.95
Fig. 19.10 Data from the Titles table of Books.
2002 Prentice Hall. All rights reserved.
16
19.3 Relational Database Overview: Books Database
0130856118
The Complete Internet and World Wide Web Programming Training Course
1 2 2000 iw3ctc1.jpg
$109.95
0130125075
Java How to Program (Java 2)
3 1 2000 jhtp3.jpg
$69.95
0130852481
The Complete Java 2 Training Course
3 2 2000 javactc3.jpg
$109.95
0130323640
e-Business and e-Commerce for Managers
1 1 2000 ebecm.jpg
$69.95
0130161438
Internet and World Wide Web How to Program
1 1 2000 iw3htp1.jpg
$69.95
0130132497
Getting Started with Visual C++ 6 with an Introduction to MFC
1 1 1999 gsvc.jpg $49.95
0130829293
The Complete Visual Basic 6 Training Course
1 2 1999 vbctc1.jpg
$109.95
0134569555
Visual Basic 6 How to Program
1 1 1999 vbhtp1.jpg
$69.95
0132719746
Java Multimedia Cyber Classroom
1 2 1998 javactc.jpg
$109.95
Fig. 19.10 Data from the Titles table of Books.
2002 Prentice Hall. All rights reserved.
17
19.3 Relational Database Overview: Books Database
0136325890
Java How to Program
1 1 1998 jhtp1.jpg $0.00
0139163050
The Complete C++ Training Course
2 2 1998 cppctc2.jpg
$109.95
0135289106
C++ How to Program
2 1 1998 cpphtp2.jpg
$49.95
0137905696
The Complete Java Training Course
2 2 1998 javactc2.jpg
$109.95
0130829277
The Complete Java Training Course (Java 1.1)
2 2 1998 javactc2.jpg
$99.95
0138993947
Java How to Program (Java 1.1)
2 1 1998 jhtp2.jpg $49.95
0131173340
C++ How to Program
1 1 1994 cpphtp1.jpg
$69.95
0132261197
C How to Program
2 1 1994 chtp2.jpg $49.95
0131180436
C How to Program
1 1 1992 chtp.jpg $69.95
Fig. 19.10 Data from the Titles table of Books.
Fig. 19.10 Data from the Titles table of Books.
2002 Prentice Hall. All rights reserved.
18
19.3 Relational Database Overview: Books Database
Fig. 19.11 Table relationships in Books.
AuthorISBN
authorID
isbn
AuthorsauthorID
firstNamelastName
Publishers
publisherID
publisherName
Titles
isbn
titleeditionNumber
copyright
publisherIDimageFile
price
1
11
2002 Prentice Hall. All rights reserved.
19
19.4 Structured Query Language (SQL)
• Used to request data (perform queries) and manipulate data
2002 Prentice Hall. All rights reserved.
20
19.4 Structured Query Language (SQL)
SQL keyword Description SELECT Select (retrieve) fields from one or more tables.
FROM Tables from which to get fields or delete records. Required in every SELECT and DELETE.
WHERE Criteria for selection that determine the rows to be retrieved.
INNER JOIN Join records from multiple tables to produce a single set of records.
GROUP BY Criteria for grouping records.
ORDER BY Criteria for ordering records.
INSERT Insert data into a specified table.
UPDATE Update data in a specified table
DELETE Delete data from a specified table.
Fig. 19.12 SQL query keywords.
Fig. 19.12 SQL query keywords.
2002 Prentice Hall. All rights reserved.
21
19.4.1Basic Select Query
• Extracts information from one or more tables in a database
• Format:– Basic: SELECT * FROM tableName
– Example: SELECT * FROM Authors
– * extracts all columns
– To get specific fields use a comma separated list instead of *
2002 Prentice Hall. All rights reserved.
22
19.4.1 Basic Select Query
authorID lastName 1 Deitel
2 Deitel
3 Nieto
4 Steinbuhler
5 Santry
6 Lin
7 Sadhu
8 McPhie
9 Yaeger
10 Zlatkina
11 Wiedermann
12 Liperi
Fig. 19.13 authorID and lastName from the Authors table.
Fig. 19.13 authorID and lastName from the Authors table.
2002 Prentice Hall. All rights reserved.
23
19.4.2 Where Clause
• Used to specify certain criteria in a query• Basic form:
– SELECT * FROM tableName WHERE criteria
• Example:– SELECT * FROM Titles WHERE copyright > 1999
• Can use LIKE clause– Used for pattern matching
• Uses wildcards
– *: zero or more characters take its place
– ?: exactly one character takes its place
2002 Prentice Hall. All rights reserved.
24
19.4.2 WHERE Clause
Title editionNumber copyright Internet and World Wide Web How to Program 2 2002
Java How to Program 4 2002
The Complete Java Training Course 4 2002
The Complete e-Business & e-Commerce Programming Training Course
1 2001
The Complete Internet & World Wide Web Programming Training Course
2 2001
The Complete Perl Training Course 1 2001
The Complete XML Programming Training Course 1 2001
C How to Program 3 2001
C++ How to Program 3 2001
The Complete C++ Training Course 3 2001
e-Business and e-Commerce How to Program 1 2001
Internet and World Wide Web How to Program 1 2000
The Complete Internet and World Wide Web Programming Training Course
1 2000
Java How to Program (Java 2) 3 2000
The Complete Java 2 Training Course 3 2000
XML How to Program 1 2001
Perl How to Program 1 2001
Advanced Java 2 Platform How to Program 1 2002
e-Business and e-Commerce for Managers 1 2000
Wireless Internet and Mobile Business How to Program 1 2001
C# How To Program 1 2002
Python How to Program 1 2002
Visual Basic .NET How to Program 2 2002
Fig. 19.14 Titles with copyrights after 1999 from table Titles.
Fig. 19.14 Titles with copyrights after 1999 from table Titles.
2002 Prentice Hall. All rights reserved.
25
19.4.2 WHERE Clause
authorID firstName lastName
1 Harvey Deitel
2 Paul Deitel
Fig. 19.15 Authors whose last names start with D from the Authors table.
Fig. 19.15 Authors whose last names start with D from the Authors table.
authorID firstName lastName 3 Tem Nieto
6 Ted Lin
11 Ben Wiedermann
12 Jonathan Liperi
Fig. 19.16 The authors from the Authors table whose last names contain i as their second letter.
Fig. 19.16 The authors from the Authors table whose last names contain i as their second letter.
2002 Prentice Hall. All rights reserved.
26
19.4.3 ORDER BY Clause
• Used to arrange results of a query– Can be ascending or descending order
• Uses ASC and DESC respectively
• Example:– SELECT authorID FROM Authors ORDER BY authorID ASC
• Can be used to sort by multiple fields
2002 Prentice Hall. All rights reserved.
27
19.4.3 ORDER BY Clause
authorID firstName lastName 2 Paul Deitel
1 Harvey Deitel
6 Ted Lin
12 Jonathan Liperi
8 David McPhie
3 Tem Nieto
7 Praveen Sadhu
5 Sean Santry
4 Kate Steinbuhler
11 Ben Wiedermann
9 Cheryl Yaeger
10 Marina Zlatkina
Fig. 19.17 Authors from table Authors in ascending order by lastName.
Fig. 19.17 Authors from table Authors in ascending order by lastName.
2002 Prentice Hall. All rights reserved.
28
19.4.3 ORDER BY Clause
authorID firstName lastName 10 Marina Zlatkina
9 Cheryl Yaeger
11 Ben Wiedermann
4 Kate Steinbuhler
5 Sean Santry
7 Praveen Sadhu
3 Tem Nieto
8 David McPhie
12 Jonathan Liperi
6 Ted Lin
2 Paul Deitel
1 Harvey Deitel
Fig. 19.18 Authors from table Authors in descending order by lastName.
Fig. 19.18 Authors from table Authors in descending order by lastName.
2002 Prentice Hall. All rights reserved.
29
19.4.3 ORDER BY Clause
authorID firstName lastName 1 Harvey Deitel
2 Paul Deitel
6 Ted Lin
12 Jonathan Liperi
8 David McPhie
3 Tem Nieto
7 Praveen Sadhu
5 Sean Santry
4 Kate Steinbuhler
11 Ben Wiedermann
9 Cheryl Yaeger
10 Marina Zlatkina
Fig. 19.19 Authors from table Authors in ascending order by lastName and by firstName.
Fig. 19.19 Authors from table Authors in ascending order by lastName and by firstName.
2002 Prentice Hall. All rights reserved.
30
19.4.3 ORDER BY Clause
isbn title edition-Number
copy-right price
0130895601 Advanced Java 2 Platform How to Program
1 2002 $69.95
0131180436 C How to Program 1 1992 $69.95
0130895725 C How to Program 3 2001 $69.95
0132261197 C How to Program 2 1994 $49.95
0130622214 C# How To Program 1 2002 $69.95
0135289106 C++ How to Program 2 1998 $49.95
0131173340 C++ How to Program 1 1994 $69.95
0130895717 C++ How to Program 3 2001 $69.95
013028419X e-Business and e-Commerce How to Program
1 2001 $69.95
0130308978 Internet and World Wide Web How to Program
2 2002 $69.95
0130161438 Internet and World Wide Web How to Program
1 2000 $69.95
0130341517 Java How to Program 4 2002 $69.95
0136325890 Java How to Program 1 1998 $0.00
0130284181 Perl How to Program 1 2001 $69.95
0130923613 Python How to Program 1 2002 $69.95
0130293636 Visual Basic .NET How to Program
2 2002 $69.95
0134569555 Visual Basic 6 How to Program
1 1999 $69.95
0130622265 Wireless Internet and Mobile Business How to Program
1 2001 $69.95
0130284173 XML How to Program 1 2001 $69.95
Fig. 19.20 Books from table Titles whose titles end with How to Program in ascending order by title.
Fig. 19.20 Books from table Titles whose titles end with How to Program in ascending order by title.
2002 Prentice Hall. All rights reserved.
31
19.4.4 Merging Data from Multiple Tables: INNER JOIN
• INNER JOIN – Merges records from multiple tables into a single record
– Tests for matching values in a common field
– General Form: SELECT * FROM table1 INNER JOIN table2 ON table1.fieldName=table2.fieldName
– Example: SELECT firstName, isbn FROM Authors INNER JOIN AuthorISBN ON Authors.authorID= AuthorISBN.authorID
• Fully-qualified names use the table name and dot operator followed by the field name
2002 Prentice Hall. All rights reserved.
32
19.4.4 Merging Data from Multiple Tables: INNER JOIN
firstName lastName isbn firstName lastName isbn
Harvey Deitel 0130895601 Paul Deitel 0134569555
Harvey Deitel 0130284181 Paul Deitel 0130829277
Harvey Deitel 0130284173 Paul Deitel 0130852473
Harvey Deitel 0130829293 Paul Deitel 0138993947
Harvey Deitel 0134569555 Paul Deitel 0130125075
Harvey Deitel 0130829277 Paul Deitel 0130856118
Harvey Deitel 0130852473 Paul Deitel 0130161438
Harvey Deitel 0138993947 Paul Deitel 013028419x
Harvey Deitel 0130125075 Paul Deitel 0139163050
Harvey Deitel 0130856118 Paul Deitel 0135289106
Harvey Deitel 0130161438 Paul Deitel 0130895717
Harvey Deitel 013028419x Paul Deitel 0132261197
Harvey Deitel 0139163050 Paul Deitel 0130895725
Harvey Deitel 0135289106 Tem Nieto 0130284181
Harvey Deitel 0130895717 Tem Nieto 0130284173
Harvey Deitel 0132261197 Tem Nieto 0130829293
Harvey Deitel 0130895725 Tem Nieto 0134569555
Paul Deitel 0130895601 Tem Nieto 0130856118
Paul Deitel 0130284181 Tem Nieto 0130161438
Paul Deitel 0130284173 Tem Nieto 013028419x
Paul Deitel 0130829293 Sean Santry 0130895601
Fig. 19.21 Portion of the authors and the ISBN numbers for the books they have written in ascending order by lastName and firstName.
Fig. 19.21 Portion of the authors and the ISBN numbers for the books they have written in ascending order by lastName and firstName.
2002 Prentice Hall. All rights reserved.
3319.4.5 Joining Data from Tables Authors, AuthorISBN, Titles and
Publishers• Tables produced by INNER JOIN can be used as
arguments for another INNER JOIN
2002 Prentice Hall. All rights reserved.
3419.4.5 Joining Data from Tables Authors, AuthorISBN, Titles and
Publishers
1 SELECT Titles.title, Titles.isbn, Authors.firstName, 2 Authors.lastName, Titles.copyright, 3 Publishers.publisherName4 FROM5 ( Publishers INNER JOIN Titles 6 ON Publishers.publisherID = Titles.publisherID ) 7 INNER JOIN8 ( Authors INNER JOIN AuthorISBN 9 ON Authors.authorID = AuthorISBN.authorID ) 10 ON Titles.isbn = AuthorISBN.isbn11 ORDER BY Titles.title
Fig. 19.22 TitleAuthor query of Books database.
Join Publishers and Titles tables if the publisherID matches
Join Authors and AuthorISBN if authorID matches
Join two created tables if titlesISBN matches authorsISBN
Sort new table by title
2002 Prentice Hall. All rights reserved.
3519.4.5 Joining Data from Tables Authors, AuthorISBN, Titles and
PublishersTitle isbn first-
Name last-Name
copy-right
publisher-Name
Advanced Java 2 Platform How to Program
0130895601 Paul Deitel 2002 Prentice Hall
Advanced Java 2 Platform How to Program
0130895601 Harvey Deitel 2002 Prentice Hall
Advanced Java 2 Platform How to Program
0130895601 Sean Santry 2002 Prentice Hall
C How to Program 0131180436 Harvey Deitel 1992 Prentice Hall
C How to Program 0131180436 Paul Deitel 1992 Prentice Hall
C How to Program 0132261197 Harvey Deitel 1994 Prentice Hall
C How to Program 0132261197 Paul Deitel 1994 Prentice Hall
C How to Program 0130895725 Harvey Deitel 2001 Prentice Hall
C How to Program 0130895725 Paul Deitel 2001 Prentice Hall
C# How To Program 0130622214 Tem Nieto 2002 Prentice Hall
C# How To Program 0130622214 Paul Deitel 2002 Prentice Hall
C# How To Program 0130622214 Cheryl Yaeger 2002 Prentice Hall
C# How To Program 0130622214 Marina Zlatkina 2002 Prentice Hall
C# How To Program 0130622214 Harvey Deitel 2002 Prentice Hall
C++ How to Program 0130895717 Paul Deitel 2001 Prentice Hall
C++ How to Program 0130895717 Harvey Deitel 2001 Prentice Hall
C++ How to Program 0131173340 Paul Deitel 1994 Prentice Hall
C++ How to Program 0131173340 Harvey Deitel 1994 Prentice Hall
C++ How to Program 0135289106 Harvey Deitel 1998 Prentice Hall
C++ How to Program 0135289106 Paul Deitel 1998 Prentice Hall
Fig. 19.23 Portion of the result set produced by the query in Fig. 19.22.
2002 Prentice Hall. All rights reserved.
3619.4.5 Joining Data from Tables Authors, AuthorISBN, Titles and
Publishers
e-Business and e-Commerce for Managers
0130323640 Harvey Deitel 2000 Prentice Hall
e-Business and e-Commerce for Managers
0130323640 Kate Steinbuhler
2000 Prentice Hall
e-Business and e-Commerce for Managers
0130323640 Paul Deitel 2000 Prentice Hall
e-Business and e-Commerce How to Program
013028419X Harvey Deitel 2001 Prentice Hall
e-Business and e-Commerce How to Program
013028419X Paul Deitel 2001 Prentice Hall
e-Business and e-Commerce How to Program
013028419X Tem Nieto 2001 Prentice Hall
Fig. 19.23 Portion of the result set produced by the query in Fig. 19.22.
Fig. 19.23 Portion of the result set produced by the query in Fig. 19.22.
2002 Prentice Hall. All rights reserved.
37
19.4.6 Insert Statement
• Inserts a new record into a table• Form: INSERT INTO tableName(fieldName1) VALUES (value1)
• Values must match field names in order and type
2002 Prentice Hall. All rights reserved.
38
19.4.6 INSERT Statement
authorID firstName lastName 1 Harvey Deitel
2 Paul Deitel
3 Tem Nieto
4 Kate Steinbuhler
5 Sean Santry
6 Ted Lin
7 Praveen Sadhu
8 David McPhie
9 Cheryl Yaeger
10 Marina Zlatkina
11 Ben Wiedermann
12 Jonathan Liperi
13 Sue Smith
Fig. 19.24 Table Authors after an INSERT INTO operation to add a record.
Fig. 19.24 Table Authors after an INSERT INTO operation to add a record.
2002 Prentice Hall. All rights reserved.
39
19.4.7 UPDATE Statement
• Modifies data in a table• Form: UPDATE tableName SET fieldName1 =
value1 WHERE criteria
2002 Prentice Hall. All rights reserved.
40
19.4.7 UPDATE Statement
authorID firstName lastName 1 Harvey Deitel
2 Paul Deitel
3 Tem Nieto
4 Kate Steinbuhler
5 Sean Santry
6 Ted Lin
7 Praveen Sadhu
8 David McPhie
9 Cheryl Yaeger
10 Marina Zlatkina
11 Ben Wiedermann
12 Jonathan Liperi
13 Sue Jones
Fig. 19.25 Table Authors after an UPDATE operation to change a record.
Fig. 19.25 Table Authors after an UPDATE operation to change a record.
2002 Prentice Hall. All rights reserved.
41
19.4.8 DELETE Statement
• Removes data from a table• Form: DELETE FROM tableName WHERE criteria
2002 Prentice Hall. All rights reserved.
42
19.4.8 DELETE Statement
authorID firstName lastName 1 Harvey Deitel
2 Paul Deitel
3 Tem Nieto
4 Kate Steinbuhler
5 Sean Santry
6 Ted Lin
7 Praveen Sadhu
8 David McPhie
9 Cheryl Yaeger
10 Marina Zlatkina
11 Ben Wiedermann
12 Jonathan Liperi
Fig. 19.26 Table Authors after a DELETE operation to remove a record.
Fig. 19.26 Table Authors after a DELETE operation to remove a record.
2002 Prentice Hall. All rights reserved.
43
19.5 ADO .NET and Object Model
• Provides an API for accessing database systems programmatically
• Namespaces:– System.Data
• System.Data.DataSet: DataTables and their relationships represent a cache of data. Store data from source in local memory
– System.Data.OleDb: classes to work with any datasource• OleDbConnection: a connect to a datasource• OleDbDataAdapter: connect to a datasource through an instance of
OleDbConnection and can populate DataSet with data from a datasource • OleDbCommand: represent a SQL command to be executed on a
datasource. Do not cache data in local memory
– System.Data.SqlClient: classes that are optimized to work with MS SQL Server 2000
2002 Prentice Hall. All rights reserved.
4419.6 Programming with ADO .NET: Extracting Information from a DBMS
• Examples that demonstrate how to connect to a database, query the database and display the results of the query1. 工具 -> 連接資料庫
– MicroSoft Jet 4.0 OLE DB Provider
– 選擇 Access 資料庫2. 在 “伺服器總管” 拖曳 資料庫 至 表單 以 產生
OldDbConnection1
3. 在 “資料” 拖曳 OldDbDataAdapter 至表單 , 在精靈的問項保留預設值 , 按 “查詢產生器” , 選擇 Authors 表格 , 在 ‘ *’ 左邊打
4. 在 “資料” 拖曳 DataSet, 選擇 “不具型別資料集”5. 在程式碼第 12 行 ( initializeComponent ) 之後加上 OleDbDataAdapter1.Fill(DataSet1, "Authors")
DataGrid1.SetDataBinding(DataSet1, "Authors")
2002 Prentice Hall. All rights reserved.
45
19.6.1 Connecting to and Querying an Access Data Source
• Retrieves data and stores it in a DataGrid
2002 Prentice Hall.All rights reserved.
Outline46
DisplayTable.vb
1 ' Fig. 19.27: DisplayTable.vb2 ' Displaying data from a database table.3 4 Public Class FrmTableDisplay5 Inherits System.Windows.Forms.Form6 7 #Region " Windows Form Designer generated code "8 9 Public Sub New()10 MyBase.New()11 12 ' This call is required by the Windows Form Designer.13 InitializeComponent()14 15 ' Add any initialization after the 16 ' InitializeComponent() call17 18 ' fill DataSet11 with data19 OleDbDataAdapter1.Fill(DataSet1, "Authors")20 21 ' bind data in Users table in dataSet11 to dgdAuthors22 dgdAuthors.SetDataBinding(DataSet1, "Authors")23 End Sub ' New24 25 ' Form overrides dispose to clean up the component list.26 Protected Overloads Overrides Sub Dispose( _27 ByVal disposing As Boolean)28 29 If disposing Then30 If Not (components Is Nothing) Then31 components.Dispose()32 End If33 End If34 MyBase.Dispose(disposing)35 End Sub ' Dispose
Constructor to populate dataSet1
Call method fill to retrieve data from database associated with oleDbConnection
Bind DataGrid to data source
2002 Prentice Hall.All rights reserved.
Outline47
DisplayTable.vb
36 37 Friend WithEvents dgdAuthors As System.Windows.Forms.DataGrid38 Friend WithEvents OleDbSelectCommand1 As _39 System.Data.OleDb.OleDbCommand40 41 Friend WithEvents OleDbInsertCommand1 As _42 System.Data.OleDb.OleDbCommand43 44 Friend WithEvents OleDbUpdateCommand1 As _45 System.Data.OleDb.OleDbCommand46 47 Friend WithEvents OleDbDeleteCommand1 As _48 System.Data.OleDb.OleDbCommand49 50 Friend WithEvents OleDbConnection1 As _51 System.Data.OleDb.OleDbConnection52 53 Friend WithEvents OleDbDataAdapter1 As _54 System.Data.OleDb.OleDbDataAdapter55 56 Friend WithEvents DataSet1 As System.Data.DataSet57 58 ' Required by the Windows Form Designer59 Private components As System.ComponentModel.Container60 61 ' NOTE: The following procedure is required by the 62 ' Windows Form Designer63 ' It can be modified using the Windows Form Designer. 64 ' Do not modify it using the code editor.65 <System.Diagnostics.DebuggerStepThrough()> _66 Private Sub InitializeComponent()67 68 Me.dgdAuthors = New System.Windows.Forms.DataGrid()69 Me.OleDbSelectCommand1 = _70 New System.Data.OleDb.OleDbCommand()
2002 Prentice Hall.All rights reserved.
Outline48
DisplayTable.vb
71 72 Me.OleDbInsertCommand1 = _73 New System.Data.OleDb.OleDbCommand()74 75 Me.OleDbUpdateCommand1 = _76 New System.Data.OleDb.OleDbCommand()77 78 Me.OleDbDeleteCommand1 = _79 New System.Data.OleDb.OleDbCommand()80 81 Me.OleDbConnection1 = _82 New System.Data.OleDb.OleDbConnection()83 84 Me.OleDbDataAdapter1 = _85 New System.Data.OleDb.OleDbDataAdapter()86 87 Me.DataSet1 = New System.Data.DataSet()88 CType(Me.dgdAuthors, _89 System.ComponentModel.ISupportInitialize).BeginInit()90 91 CType(Me.DataSet1, _92 System.ComponentModel.ISupportInitialize).BeginInit()93 94 Me.SuspendLayout()95 96 '97 ' dgdAuthors98 '99 Me.dgdAuthors.DataMember = ""100 Me.dgdAuthors.Location = New System.Drawing.Point(8, 8)101 Me.dgdAuthors.Name = "dgdAuthors"102 Me.dgdAuthors.Size = New System.Drawing.Size(304, 256)103 Me.dgdAuthors.TabIndex = 0104
2002 Prentice Hall.All rights reserved.
Outline49
DisplayTable.vb
105 '106 ' OleDbSelectCommand1107 '108 Me.OleDbSelectCommand1.CommandText = _109 "SELECT authorID, firstName, lastName FROM Authors"110 111 Me.OleDbSelectCommand1.Connection = Me.OleDbConnection1112 113 '114 ' OleDbInsertCommand1115 '116 Me.OleDbInsertCommand1.CommandText = _117 "INSERT INTO Authors(authorID, firstName, lastName)" & _118 "VALUES (?, ?, ?)"119 120 Me.OleDbInsertCommand1.Connection = _121 Me.OleDbConnection1122 123 Me.OleDbInsertCommand1.Parameters.Add _124 (New System.Data.OleDb.OleDbParameter("authorID", _125 System.Data.OleDb.OleDbType.Numeric, 0, _126 System.Data.ParameterDirection.Input, False, _127 CType(10, Byte), CType(0, Byte), "authorID", _128 System.Data.DataRowVersion.Current, Nothing))129 130 Me.OleDbInsertCommand1.Parameters.Add _131 (New System.Data.OleDb.OleDbParameter("firstName", _132 System.Data.OleDb.OleDbType.Char, 50, _133 System.Data.ParameterDirection.Input, False, _134 CType(0, Byte), CType(0, Byte), "firstName", _135 System.Data.DataRowVersion.Current, Nothing))136
2002 Prentice Hall.All rights reserved.
Outline50
DisplayTable.vb
137 Me.OleDbInsertCommand1.Parameters.Add _138 (New System.Data.OleDb.OleDbParameter("lastName", _139 System.Data.OleDb.OleDbType.Char, 50, _140 System.Data.ParameterDirection.Input, False, _141 CType(0, Byte), CType(0, Byte), "lastName", _142 System.Data.DataRowVersion.Current, Nothing))143 144 '145 ' OleDbUpdateCommand1146 '147 Me.OleDbUpdateCommand1.CommandText = _148 "UPDATE Authors SET authorID = ?, firstName = ?, " & _149 "lastName = ? WHERE (authorID = ?)" & _150 " AND (firstName = ?) AND (lastName = ?)"151 152 Me.OleDbUpdateCommand1.Connection = Me.OleDbConnection1153 Me.OleDbUpdateCommand1.Parameters.Add _154 (New System.Data.OleDb.OleDbParameter("authorID", _155 System.Data.OleDb.OleDbType.Numeric, 0, _156 System.Data.ParameterDirection.Input, False, _157 CType(10, Byte), CType(0, Byte), "authorID", _158 System.Data.DataRowVersion.Current, Nothing))159 160 Me.OleDbUpdateCommand1.Parameters.Add _161 (New System.Data.OleDb.OleDbParameter("firstName", _162 System.Data.OleDb.OleDbType.Char, 50, _163 System.Data.ParameterDirection.Input, False, _164 CType(0, Byte), CType(0, Byte), "firstName", _165 System.Data.DataRowVersion.Current, Nothing))166
Set connection property for oleDbUpdateCommand1
Set CommandText for oleDbUpdateCommand1
2002 Prentice Hall.All rights reserved.
Outline51
DisplayTable.vb
167 Me.OleDbUpdateCommand1.Parameters.Add _168 (New System.Data.OleDb.OleDbParameter("lastName", _169 System.Data.OleDb.OleDbType.Char, 50, _170 System.Data.ParameterDirection.Input, False, _171 CType(0, Byte), CType(0, Byte), "lastName", _172 System.Data.DataRowVersion.Current, Nothing))173 174 Me.OleDbUpdateCommand1.Parameters.Add _175 (New System.Data.OleDb.OleDbParameter _176 ("Original_authorID", _177 System.Data.OleDb.OleDbType.Numeric, 0, _178 System.Data.ParameterDirection.Input, False, _179 CType(10, Byte), CType(0, Byte), "authorID", _180 System.Data.DataRowVersion.Original, Nothing))181 182 Me.OleDbUpdateCommand1.Parameters.Add _183 (New System.Data.OleDb.OleDbParameter _184 ("Original_firstName", _185 System.Data.OleDb.OleDbType.Char, 50, _186 System.Data.ParameterDirection.Input, False, _187 CType(0, Byte), CType(0, Byte), "firstName", _188 System.Data.DataRowVersion.Original, Nothing))189 190 Me.OleDbUpdateCommand1.Parameters.Add _191 (New System.Data.OleDb.OleDbParameter _192 ("Original_lastName", _193 System.Data.OleDb.OleDbType.Char, 50, _194 System.Data.ParameterDirection.Input, False, _195 CType(0, Byte), CType(0, Byte), "lastName", _196 System.Data.DataRowVersion.Original, Nothing))197
2002 Prentice Hall.All rights reserved.
Outline52
DisplayTable.vb
198 '199 ' OleDbDeleteCommand1200 '201 Me.OleDbDeleteCommand1.CommandText = _202 "DELETE FROM Authors WHERE (authorID = ?) AND " & _203 "(firstName = ?) AND (lastName = ?)"204 205 Me.OleDbDeleteCommand1.Connection = Me.OleDbConnection1206 Me.OleDbDeleteCommand1.Parameters.Add _207 (New System.Data.OleDb.OleDbParameter("authorID", _208 System.Data.OleDb.OleDbType.Numeric, 0, _209 System.Data.ParameterDirection.Input, False, _210 CType(10, Byte), CType(0, Byte), "authorID", _211 System.Data.DataRowVersion.Original, Nothing))212 213 Me.OleDbDeleteCommand1.Parameters.Add _214 (New System.Data.OleDb.OleDbParameter("firstName", _215 System.Data.OleDb.OleDbType.Char, 50, _216 System.Data.ParameterDirection.Input, False, _217 CType(0, Byte), CType(0, Byte), "firstName", _218 System.Data.DataRowVersion.Original, Nothing))219 220 Me.OleDbDeleteCommand1.Parameters.Add _221 (New System.Data.OleDb.OleDbParameter("lastName", _222 System.Data.OleDb.OleDbType.Char, 50, _223 System.Data.ParameterDirection.Input, False, _224 CType(0, Byte), CType(0, Byte), "lastName", _225 System.Data.DataRowVersion.Original, Nothing))226
2002 Prentice Hall.All rights reserved.
Outline53
DisplayTable.vb
227 '228 'OleDbConnection1229 '230 Me.OleDbConnection1.ConnectionString = _231 "Provider=Microsoft.Jet.OLEDB.4.0;Password="""";" & _232 "User ID=Admin;Data Source=C:\Documen" & _233 "ts and Settings\thiago\Desktop\vbhtp2e\examples\" & _234 "Ch19\Fig19_27\Books.mdb;Mode=Sha" & _235 "re Deny None;Extended Properties="""";" & _236 "Jet OLEDB:System database="""";Jet OLEDB:Regis" & _237 "try Path="""";Jet OLEDB:Database Password="""";" & _238 "Jet OLEDB:Engine Type=5;Jet OLEDB:Dat" & _239 "abase Locking Mode=1;Jet OLEDB:Global Partial " & _240 "Bulk Ops=2;Jet OLEDB:Global Bulk T" & _241 "ransactions=1;Jet OLEDB:New Database " & _242 "Password="""";Jet OLEDB:Create System Databas" & _243 "e=False;Jet OLEDB:Encrypt Database=False;" & _244 "Jet OLEDB:Don't Copy Locale on Compact=" & _245 "False;Jet OLEDB:Compact Without Replica " & _246 "Repair=False;Jet OLEDB:SFP=False"247 248 '249 ' OleDbDataAdapter1250 '251 Me.OleDbDataAdapter1.DeleteCommand = _252 Me.OleDbDeleteCommand1253 254 Me.OleDbDataAdapter1.InsertCommand = _255 Me.OleDbInsertCommand1256 257 Me.OleDbDataAdapter1.SelectCommand = _258 Me.OleDbSelectCommand1259
Initialize oleDbConnection, and specify path to database
Specify how oleDbDataAdapter deletes data
Specify how oleDbDataAdapter inserts data
Specify how oleDbDataAdapter selects data
2002 Prentice Hall.All rights reserved.
Outline54
DisplayTable.vb
260 Me.OleDbDataAdapter1.TableMappings.AddRange _261 (New System.Data.Common.DataTableMapping() _262 {New System.Data.Common.DataTableMapping("Table", _263 "Authors", New System.Data.Common.DataColumnMapping() _264 {New System.Data.Common.DataColumnMapping("authorID", _265 "authorID"), New System.Data.Common.DataColumnMapping _266 ("firstName", "firstName"), _267 New System.Data.Common.DataColumnMapping("lastName", _268 "lastName")})})269 270 Me.OleDbDataAdapter1.UpdateCommand = _271 Me.OleDbUpdateCommand1272 273 '274 ' DataSet1275 '276 Me.DataSet1.DataSetName = "NewDataSet"277 Me.DataSet1.Locale = _278 New System.Globalization.CultureInfo("en-US")279 280 '281 ' FrmTableDisplay282 '283 Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)284 Me.ClientSize = New System.Drawing.Size(320, 273)285 Me.Controls.AddRange(New System.Windows.Forms.Control() _286 {Me.dgdAuthors})287 288 Me.Name = "FrmTableDisplay"289 Me.Text = "Table Display"290 CType(Me.dgdAuthors, System.ComponentModel. _291 ISupportInitialize).EndInit()292 293 CType(Me.DataSet1, System.ComponentModel. _294 ISupportInitialize).EndInit()
Specify how oleDbDataAdapter updates data
2002 Prentice Hall.All rights reserved.
Outline55
DisplayTable.vb
295 296 Me.ResumeLayout(False)297 298 End Sub ' InitializeComponent299 300 #End Region301 302 End Class ' FrmTableDisplay
2002 Prentice Hall. All rights reserved.
56
19.6.2 Querying the Books Database
• Use SELECT statements on database and display results
2002 Prentice Hall.All rights reserved.
Outline57
DisplayQueryResults.vb
1 ' Fig. 19.28: DisplayQueryResults.vb2 ' Displays the contents of the authors database.3 4 Public Class FrmDisplayQueryResult5 Inherits System.Windows.Forms.Form6 7 Friend WithEvents txtQuery As System.Windows.Forms.TextBox8 Friend WithEvents cmdSubmit As System.Windows.Forms.Button9 Friend WithEvents dgdResults As System.Windows.Forms.DataGrid10 Friend WithEvents BooksConnection As _11 System.Data.OleDb.OleDbConnection12 13 Friend WithEvents BooksDataAdapter As _14 System.Data.OleDb.OleDbDataAdapter15 16 Friend WithEvents BooksDataSet As System.Data.DataSet17 18 ' Visual Studio .NET generated code19 20 ' perform SQL query on data21 Private Sub cmdSubmit_Click(ByVal sender As System.Object, _22 ByVal e As System.EventArgs) Handles cmdSubmit.Click23 24 Try25 26 ' set the text of the SQL query to what the user typed27 ' in28 BooksDataAdapter.SelectCommand.CommandText = _29 txtQuery.Text30 31 ' clear the DataSet from the previous operation32 BooksDataSet.Clear()33
Form FrmDisplayQueryResult contains TextBox txtQuery, in which users input SELECT statements
After entering a query, the user clicks Button cmdSubmit, labeled Submit Query, to view the results of the query
2002 Prentice Hall.All rights reserved.
Outline58
DisplayQueryResults.vb
Program Output
34 ' Fill the data set with the information that results35 ' from the SQL query36 BooksDataAdapter.Fill(BooksDataSet, "Authors")37 38 ' Bind the DataGrid to the contents of the DatSet39 dgdResults.SetDataBinding(BooksDataSet, "Authors")40 41 ' display database connection verbose message42 Catch exception As System.Data.OleDb.OleDbException43 MessageBox.Show("Invalid Query")44 End Try45 46 End Sub ' cmdSubmit_Click47 48 End Class ' FrmDisplayQueryResults
2002 Prentice Hall. All rights reserved.
59
19.7 Programming with ADO.NET: Modifying a DBMS
• Example implements an address book– User can insert, locate and update records
2002 Prentice Hall.All rights reserved.
Outline60
AddressBook.vb
1 ' Fig. 19.29: AddressBook.vb2 ' Using SQL statements to manipulate a database.3 4 Imports System.Windows.Forms5 6 Public Class FrmAddressBook7 Inherits Form8 9 ' top set of command buttons10 Friend WithEvents cmdFind As Button11 Friend WithEvents cmdAdd As Button12 Friend WithEvents cmdUpdate As Button13 Friend WithEvents cmdClear As Button14 Friend WithEvents cmdHelp As Button15 16 ' textbox identifier labels17 Friend WithEvents lblId As Label18 Friend WithEvents lblFirst As Label19 Friend WithEvents lblLast As Label20 Friend WithEvents lblAddress As Label21 Friend WithEvents lblCity As Label22 Friend WithEvents lblState As Label23 Friend WithEvents lblZip As Label24 Friend WithEvents lblCountry As Label25 Friend WithEvents lblEmail As Label26 Friend WithEvents lblPhone As Label27 Friend WithEvents lblFax As Label28 29 ' input textboxes30 Friend WithEvents txtId As TextBox31 Friend WithEvents txtFirst As TextBox32 Friend WithEvents txtLast As TextBox33 Friend WithEvents txtAddress As TextBox34 Friend WithEvents txtCity As TextBox35 Friend WithEvents txtState As TextBox
2002 Prentice Hall.All rights reserved.
Outline61
AddressBook.vb
36 Friend WithEvents txtZip As TextBox37 Friend WithEvents txtCountry As TextBox38 Friend WithEvents txtEmail As TextBox39 Friend WithEvents txtPhone As TextBox40 Friend WithEvents txtFax As TextBox41 42 ' query status display textbox43 Friend WithEvents txtStatus As TextBox44 45 ' database connection 46 Friend WithEvents AddressBookConnection As _47 System.Data.OleDb.OleDbConnection48 49 ' database adapter 50 Friend WithEvents AddressBookDataAdapter As _51 System.Data.OleDb.OleDbDataAdapter52 53 ' query dataset 54 Friend WithEvents AddressBookDataSet As System.Data.DataSet55 56 ' constructor57 Public Sub New()58 MyBase.New()59 60 ' This call is required by the Windows Form Designer.61 InitializeComponent()62 63 ' Add any initialization after the InitializeComponent call64 65 ' open connection66 AddressBookConnection.Open()67 End Sub ' New68 69 ' Visual Studio .NET generated code70
2002 Prentice Hall.All rights reserved.
Outline62
AddressBook.vb
71 ' finds record in database72 Private Sub cmdFind_Click(ByVal sender As System.Object, _73 ByVal e As System.EventArgs) Handles cmdFind.Click74 75 Try76 77 ' ensure user input last name78 If txtLast.Text <> "" Then79 80 ' clear DataSet from last operation81 AddressBookDataSet.Clear()82 83 ' create SQL query to find contact84 ' with specified last name85 AddressBookDataAdapter.SelectCommand.CommandText = _86 "SELECT * FROM addresses WHERE " & _87 "lastname = '" & txtLast.Text & "' "88 89 ' fill AddressBookDataSet with the rows resulting 90 ' from the query91 AddressBookDataAdapter.Fill(AddressBookDataSet)92 93 ' display information94 Display(AddressBookDataSet)95 txtStatus.Text &= vbCrLf & "Query Successful " & _96 vbCrLf97 98 ' prompt user for last name99 Else100 txtLast.Text = _101 "Enter last name here then press Find"102 End If103 104 ' display verbose information with database exception105 Catch oleDbExceptionParameter As _
Method Clear of class DataSet is invoked to empty the DataSet of any prior data
The TextBoxes are updated with a call to method Display
Event handler cmdFind_Click performs the SELECT query on the database for the record associated with the String entered in txtLast
2002 Prentice Hall.All rights reserved.
Outline63
AddressBook.vb
106 System.Data.OleDb.OleDbException107 108 Console.WriteLine(oleDbExceptionParameter.StackTrace)109 txtStatus.Text &= oleDbExceptionParameter.ToString110 111 ' display message box when invalid operation112 Catch invalidOperationExceptionParameter As _113 InvalidOperationException114 115 MessageBox.Show( _116 invalidOperationExceptionParameter.Message)117 End Try118 119 End Sub ' cmdFind_Click120 121 ' adds record to database122 Private Sub cmdAdd_Click(ByVal sender As System.Object, _123 ByVal e As System.EventArgs) Handles cmdAdd.Click124 125 Try126 127 ' ensure first and last name input128 If (txtLast.Text <> "" AndAlso txtFirst.Text <> "") Then129 130 ' create the SQL query to insert a row131 AddressBookDataAdapter.InsertCommand.CommandText = _132 "INSERT INTO addresses(firstname, " & _133 "lastname, address, city, " & _134 "stateorprovince, postalcode, country, " & _135 "emailaddress, homephone, faxnumber) " & _136 "VALUES('" & txtFirst.Text & "' , " & _137 "'" & txtLast.Text & "' , " & _138 "'" & txtAddress.Text & "' , " & _139 "'" & txtCity.Text & "' , " & _140 "'" & txtState.Text & "' , " & _
Method cmdAdd_Click performs INSERT and UPDATE operations
2002 Prentice Hall.All rights reserved.
Outline64
AddressBook.vb
141 "'" & txtZip.Text & "' , " & _142 "'" & txtCountry.Text & "' , " & _143 "'" & txtEmail.Text & "' , " & _144 "'" & txtPhone.Text & "' , " & _145 "'" & txtFax.Text & "')"146 147 ' notify the user the query is being sent 148 txtStatus.Text &= vbCrLf & "Sending query: " & _149 AddressBookDataAdapter.InsertCommand. _ 150 CommandText & vbCrLf151 152 ' send query153 AddressBookDataAdapter.InsertCommand. _154 ExecuteNonQuery()155 156 txtStatus.Text &= vbCrLf & "Query successful"157 158 ' prompt user to input first and last name159 Else160 txtStatus.Text &= vbCrLf & _161 "Enter at least first and last name then " & _162 "press Add" & vbCrLf163 End If164 165 ' display verbose information when database exception166 Catch oleDbExceptionParameter As _167 System.Data.OleDb.OleDbException168 169 Console.WriteLine(oleDbExceptionParameter.StackTrace)170 txtStatus.Text &= oleDbExceptionParameter.ToString171 End Try172 173 End Sub ' cmdAdd_Click174 175 ' updates entry in database
2002 Prentice Hall.All rights reserved.
Outline65
AddressBook.vb
176 Private Sub cmdUpdate_Click(ByVal sender As System.Object, _177 ByVal e As System.EventArgs) Handles cmdUpdate.Click178 179 Try180 181 ' make sure user has already found 182 ' record to update183 If txtId.Text <> "" Then184 185 ' set SQL query to update all fields in 186 ' table where id number matches id in 187 ' idTextBox188 AddressBookDataAdapter.UpdateCommand.CommandText = _189 "UPDATE addresses SET firstname=" & _190 "'" & txtFirst.Text & "' , " & _191 "lastname = '" & txtLast.Text & "' , " & _192 "address='" & txtAddress.Text & "' , " & _193 "city='" & txtCity.Text & "' , " & _194 "stateorprovince= " & _195 "'" & txtState.Text & "', " & _196 "postalcode='" & txtZip.Text & "', " & _197 "country='" & txtCountry.Text & "' , " & _198 "emailaddress='" & txtEmail.Text & "' , " & _199 "homephone='" & txtPhone.Text & "' , " & _200 "faxnumber='" & txtFax.Text & "' " & _201 "WHERE id=" & txtId.Text & " ; "202203 ' notify user that query is being sent204 txtStatus.Text &= vbCrLf & "Sending query: " & _205 AddressBookDataAdapter.UpdateCommand. _206 CommandText & vbCrLf207208 ' execute query209 AddressBookDataAdapter.UpdateCommand. _210 ExecuteNonQuery()
2002 Prentice Hall.All rights reserved.
Outline66
AddressBook.vb
211212 txtStatus.Text &= vbCrLf & "Query Successful" & _213 vbCrLf214215 ' prompt user to input existing record216 Else217 txtStatus.Text &= vbCrLf & _218 "You may only update an existing record. " & _219 "Use Find to locate the record, then " & _220 "modify the information and press Update." & _221 vbCrLf222 End If223224 ' display verbose information when database exception225 Catch oleDbExceptionParameter As _226 System.Data.OleDb.OleDbException227228 Console.WriteLine(oleDbExceptionParameter.StackTrace)229 txtStatus.Text &= oleDbExceptionParameter.ToString230 End Try231232 End Sub ' cmdUpdate_Click233234 ' clears all information in textboxes235 Private Sub cmdClear_Click(ByVal sender As System.Object, _236 ByVal e As System.EventArgs) Handles cmdClear.Click237238 txtId.Clear()239 ClearTextBoxes()240 End Sub ' cmdClear_Click241242 ' displays information on application use243 Private Sub cmdHelp_Click(ByVal sender As System.Object, _244 ByVal e As System.EventArgs) Handles cmdHelp.Click245
2002 Prentice Hall.All rights reserved.
Outline67
AddressBook.vb
246 txtStatus.AppendText(vbCrLf & _247 "Click Find to locate a record" & vbCrLf & _248 "Click Add to insert a new record." & vbCrLf & _249 "Click Update to update the information in a " & _250 "record " & vbCrLf & "Click Clear to empty the " & _ 251 "textboxes")252 End Sub ' cmdHelp_Click253254 ' displays data in dataset255 Private Sub Display(ByVal dataset As DataSet)256257 Try258259 ' get first DataTable - there will be one260 Dim dataTable As DataTable = dataset.Tables(0)261262 ' ensure dataTable not empty263 If dataTable.Rows.Count <> 0 Then264 Dim recordNumber As Integer = _265 Convert.ToInt32(dataTable.Rows(0)(0))266267 txtId.Text = recordNumber.ToString268 txtFirst.Text = _269 Convert.ToString(dataTable.Rows(0)(1))270271 txtLast.Text = _272 Convert.ToString(dataTable.Rows(0)(2))273274 txtAddress.Text = _275 Convert.ToString(dataTable.Rows(0)(3))276277 txtCity.Text = _278 Convert.ToString(dataTable.Rows(0)(4))279280 txtState.Text = _
Retrieve the remaining fields of data from the DataTable to populate the user interface
Retrieves the field with index 0, 0 and stores the value in variable recordNumber
Checks whether the query returned any rows
Method Display updates the user interface with data from the newly retrieved address book record
2002 Prentice Hall.All rights reserved.
Outline68
AddressBook.vb
281 Convert.ToString(dataTable.Rows(0)(5))282283 txtZip.Text = _284 Convert.ToString(dataTable.Rows(0)(6))285286 txtCountry.Text = _287 Convert.ToString(dataTable.Rows(0)(7))288289 txtEmail.Text = _290 Convert.ToString(dataTable.Rows(0)(8))291292 txtPhone.Text = _293 Convert.ToString(dataTable.Rows(0)(9))294295 txtFax.Text = _296 Convert.ToString(dataTable.Rows(0)(10))297298 ' display not-found message299 Else300 txtStatus.Text &= vbCrLf & "No record found“ & vbCrLf301 End If302303 ' display verbose information when database exception304 Catch oleDbExceptionParameter As _305 System.Data.OleDb.OleDbException306307 Console.WriteLine(oleDbExceptionParameter.StackTrace)308 txtStatus.Text &= oleDbExceptionParameter.ToString309 End Try310311 End Sub ' Display 312313 ' clears text boxes314 Private Sub ClearTextBoxes()315 txtFirst.Clear()
The Clear button clears the text from the TextBoxes using method ClearTextBoxes
2002 Prentice Hall.All rights reserved.
Outline69
AddressBook.vb
316 txtLast.Clear()317 txtAddress.Clear()318 txtCity.Clear()319 txtState.Clear()320 txtZip.Clear()321 txtCountry.Clear()322 txtEmail.Clear()323 txtPhone.Clear()324 txtFax.Clear()325 End Sub ' ClearTextBoxes326327 End Class ' FrmAddressBook
2002 Prentice Hall.All rights reserved.
Outline70
AddressBook.vb
2002 Prentice Hall.All rights reserved.
Outline71
AddressBook.vb
2002 Prentice Hall.All rights reserved.
Outline72
AddressBook.vb
2002 Prentice Hall.All rights reserved.
Outline73
AddressBook.vb
2002 Prentice Hall. All rights reserved.
74
19.8 Reading and Writing XML Files
• ADO.NET can convert data from data source into XML files– Uses methods WriteXml, ReadXml andGetXml
2002 Prentice Hall.All rights reserved.
Outline75
XMLWriter.vb
1 ' Fig. 19.30 XMLWriter.vb2 ' Demonstrates generating XML from an ADO.NET DataSet3 4 Public Class FrmXMLWriter5 Inherits System.Windows.Forms.Form6 7 ' constructor8 Public Sub New()9 MyBase.New()10 11 ' This call is required by the Windows Form Designer.12 InitializeComponent()13 14 ' Add any initialization after the 15 ' InitializeComponent() call16 17 ' open database connection18 BaseballConnection.Open()19 20 ' fill DataSet with data from OleDbDataAdapter21 BaseballDataAdapter.Fill(BaseballDataSet, "Players")22 23 ' bind DataGrid to DataSet24 dgdPlayers.SetDataBinding(BaseballDataSet, "Players")25 End Sub26 27 Friend WithEvents cmdWrite As System.Windows.Forms.Button28 Friend WithEvents dgdPlayers As System.Windows.Forms.DataGrid29 Friend WithEvents txtOutput As System.Windows.Forms.TextBox30 Friend WithEvents BaseballConnection As _31 System.Data.OleDb.OleDbConnection32 33 Friend WithEvents BaseballDataAdapter As _34 System.Data.OleDb.OleDbDataAdapter35
Establishes a connection to the Baseball databaseMethod Fill of class OleDbDataAdapter is called to populate BaseballDataSet with data from the Players table in the Baseball database
Binds the dgdPlayers to BaseballDataSet to display the information to the user
2002 Prentice Hall.All rights reserved.
Outline76
XMLWriter.vb
36 Friend WithEvents BaseballDataSet As System.Data.DataSet37 38 ' Visual Studio .NET generated code 39 40 ' write XML representation of DataSet when button clicked41 Private Sub cmdWrite_Click(ByVal sender As System.Object, _42 ByVal e As System.EventArgs) Handles cmdWrite.Click43 44 ' write XML representation of DataSet to file45 BaseballDataSet.WriteXml("Players.xml")46 47 ' display XML in TextBox48 txtOutput.Text &= "Writing the following XML:" & _49 vbCrLf & BaseballDataSet.GetXml() & vbCrLf50 End Sub ' cmWrite_Click51 52 End Class ' FrmXMLWriter
DataSet method WriteXml is invoked to generate an XML representation of the data contained in the DataSet and then writes the XML to the specified file
2002 Prentice Hall. All rights reserved.
77
19.8 Reading and Writing XML Documents
1 <?xml version="1.0" standalone="yes"?>2 <NewDataSet>3 <Players>4 <firstName>John</firstName>5 <lastName>Doe</lastName>6 <battingAverage>0.375</battingAverage>7 <playerID>1</playerID>8 </Players>9 10 <Players>11 <firstName>Jack</firstName>12 <lastName>Smith</lastName>13 <battingAverage>0.223</battingAverage>14 <playerID>2</playerID>15 </Players>16 17 <Players>18 <firstName>George</firstName>19 <lastName>O'Malley</lastName>20 <battingAverage>0.444</battingAverage>21 <playerID>3</playerID>22 </Players>23 </NewDataSet>
Fig. 19.31 XML document generated from DataSet in DatabaseXMLWriter.
top related