c# and databases - city university of new york · 1 csc 330 object oriented programming c# and...

13
1 CSC 330 Object Oriented CSC 330 Object Oriented Programming Programming C# and Databases C# and Databases Introduction Introduction Database: Integrated collection of data Database management system (DBMS) Provides mechanisms for storing and organizing data in a 2 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 What are Databases? What are Databases? Features of Database management system (DBMS) Definition of data structure Maintenance facility 3 a te a ce ac ty Allow access to and storage of data independently of the internal representation of data Main job of the DBMS is to ensure ensure data data integrity integrity Relational Database Systems and SQL Relational Database Systems and SQL Relational database systems are the most popular today (Microsoft Access is a relational database system) SQL is international standard language used with relational dtb t t f i (i t t 4 database systems to perform queries (i.e. to request information that satisfies given criteria) and to manipulate data Some popular relational database management systems (RDBMS) are Microsoft SQL Server, Oracle, MySQL, Sybase Relational Database Model Relational Database Model Logical representation of data: Relationships can be considered without concern for physical structure of data Composed of tables 5 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 Relational Database Model Relational Database Model Relational Database Model Relational Database Model All information is contained in tables (or relations relations) Tuple Tuple or row (record) Attribute Attribute or column (field) Relationships [not why called relational] 6 Relationships [not why called relational]

Upload: others

Post on 31-Jan-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C# and Databases - City University of New York · 1 CSC 330 Object Oriented Programming C# and Databases Introduction Database: Integrated colle ction of data Database management

1

CSC 330 Object Oriented CSC 330 Object Oriented ProgrammingProgramming

C# and DatabasesC# and Databases

IntroductionIntroduction

Database:Integrated collection of dataDatabase management system (DBMS)

Provides mechanisms for storing and organizing data in a

2

Provides mechanisms for storing and organizing data in a way that is consistent with database’s formatAllows storage and access to database without knowledge of internal representation

Relational Databases most popularUse Structured Query Language to perform queries (search) and manipulate dataProgramming languages need an interface to interact with relational databases

What are Databases?What are Databases?

Features of Database management system (DBMS)Definition of data structure Maintenance facility

3

a te a ce ac tyAllow access to and storage of data independently of the internal representation of data

Main job of the DBMS is to ensureensure datadata integrityintegrity

Relational Database Systems and SQLRelational Database Systems and SQL

Relational database systems are the most popular today (Microsoft Access is a relational database system)SQL is international standard language used with relational d t b t t f i (i t t

4

database systems to perform queries (i.e. to request information that satisfies given criteria) and to manipulate dataSome popular relational database management systems (RDBMS) are Microsoft SQL Server, Oracle, MySQL, Sybase

Relational Database ModelRelational Database Model

Logical representation of data:Relationships can be considered without concern for physical structure of data

Composed of tables

5

Composed of tablesRows called recordsColumns called fieldsPrimary 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

Relational Database ModelRelational Database ModelRelational Database ModelRelational Database Model

All information is contained in tables (or relationsrelations)

TupleTuple or row (record)AttributeAttribute or column (field)Relationships [not why called relational]

6

Relationships [not why called relational]

Page 2: C# and Databases - City University of New York · 1 CSC 330 Object Oriented Programming C# and Databases Introduction Database: Integrated colle ction of data Database management

2

Relation InstanceRelation InstanceThe current values (relation instance) of a relation are specified by a tableAn element t of r is a tuple, represented by a row in a table

attributes(or columns)

7

JonesSmithCurryLindsay

customer_name

MainNorthNorthPark

customer_street

HarrisonRyeRyePittsfield

customer_city

customer

tuples(or rows)

Relational Database ModelRelational Database Model

Relationships are logical representation of data:Not concerned with physical structure

PrimaryPrimary keykey: field that contains unique dataEach record can be identified by at least one distinct value

8

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

Primary KeysPrimary Keys

Relational DBMS enforces several constraints on dataRuleRule ofof EntityEntity IntegrityIntegrity: every record must have a unique value in its primary-key fieldPrimary key does not have to be a single field

9

Primary key does not have to be a single fieldCompoundCompound PrimaryPrimary KeyKey: when a record has a unique key based on a combination of two fields

Foreign KeysForeign Keys

A foreignforeign keykey is used to create relationships: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

10

key for that tableRuleRule ofof ReferentialReferential IntegrityIntegrity: every foreign-key field value must appear in another table’s primary-key fieldOneOne toto manymany relationshiprelationship: A foreign key can appear many times in its own table, but only once as primary key in another table

Relational Database Overview: Relational Database Overview: Books DatabaseBooks Database

Rule of Entity Integrity: every record must have a unique value in its primary-key fieldCompound Primary key: when a record has a unique key based on a combination of two fieldsForeign key:

11

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 tableRule of Referential Integrity: every foreign-key field value must appear in another table’s primary-key fieldOne to many relationship: A foreign key can appear many times in its own table, but only once as primary key in another table

Relational Database Overview: Relational Database Overview: BooksBooks DatabaseDatabase

Field Desc rip tion authorID Author’s ID number in the database. In the Books database, this int field is

defined as an auto-incremented field. For each new record inserted in this table, the database increments the authorID value, ensuring that each record has a unique authorID. This field represents the table’s primary key.

firstName Author’s first name (a string)

12

firstName Author s first name (a string). lastName Author’s last name (a string). Fig. 19.3 Authors tab le from Books.

Page 3: C# and Databases - City University of New York · 1 CSC 330 Object Oriented Programming C# and Databases Introduction Database: Integrated colle ction of data Database management

3

Relational Database Overview: Relational Database Overview: BooksBooks DatabaseDatabase

authorID firstName lastName 1 Harvey Deitel

2 Paul Deitel

3 Tem Nieto

4 Kate Steinbuhler

5 Sean Santry

6 Ted Lin

13

6 Ted Lin

7 Praveen Sadhu

8 David McPhie

9 Cheryl Yaeger

10 Marina Zlatkina

11 Ben Wiedermann

12 Jonathan Liperi

13 Jeffrey Listfield

Fig. 19.4 Data from the Authors tab le of Books.

Relational Database Overview: Relational Database Overview: BooksBooks DatabaseDatabase

Field Description publisherID The publisher’s ID number in the database. This auto-incremented int

field is the table’s primary-key field.

publisherName The name of the publisher (a string). Fig. 19.5 Publishers table from Books.

bli h ID bli h N

14

publisherID publisherName 1 Prentice Hall

2 Prentice Hall PTG Fig. 19.6 Data from the Publishers tab le of Books.

Field Desc rip tion 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 ta b le from Books.

Relational Database Overview: Relational Database Overview: BooksBooks DatabaseDatabase

a u t h o r I D i s b n a u t h o r I D i s b n 1 0 1 3 0 8 9 5 7 2 5 2 0 1 3 9 1 6 3 0 5 0

1 0 1 3 2 2 6 1 1 9 7 2 0 1 3 0 2 8 4 1 9 x 1 0 1 3 0 8 9 5 7 1 7 2 0 1 3 0 1 6 1 4 3 8 1 0 1 3 5 2 8 9 1 0 6 2 0 1 3 0 8 5 6 1 1 8 1 0 1 3 9 1 6 3 0 5 0 2 0 1 3 0 1 2 5 0 7 5 1 0 1 3 0 2 8 4 1 9 x 2 0 1 3 8 9 9 3 9 4 7 1 0 1 3 0 1 6 1 4 3 8 2 0 1 3 0 8 5 2 4 7 3 1 0 1 3 0 8 5 6 1 1 8 2 0 1 3 0 8 2 9 2 7 7

15

1 0 1 3 0 8 5 6 1 1 8 2 0 1 3 0 8 2 9 2 7 7 1 0 1 3 0 1 2 5 0 7 5 2 0 1 3 4 5 6 9 5 5 5 1 0 1 3 8 9 9 3 9 4 7 2 0 1 3 0 8 2 9 2 9 3 1 0 1 3 0 8 5 2 4 7 3 2 0 1 3 0 2 8 4 1 7 3 1 0 1 3 0 8 2 9 2 7 7 2 0 1 3 0 2 8 4 1 8 1 1 0 1 3 4 5 6 9 5 5 5 2 0 1 3 0 8 9 5 6 0 1 1 0 1 3 0 8 2 9 2 9 3 3 0 1 3 0 2 8 4 1 9 x 1 0 1 3 0 2 8 4 1 7 3 3 0 1 3 0 1 6 1 4 3 8 1 0 1 3 0 2 8 4 1 8 1 3 0 1 3 0 8 5 6 1 1 8 1 0 1 3 0 8 9 5 6 0 1 3 0 1 3 4 5 6 9 5 5 5 2 0 1 3 0 8 9 5 7 2 5 3 0 1 3 0 8 2 9 2 9 3 2 0 1 3 2 2 6 1 1 9 7 3 0 1 3 0 2 8 4 1 7 3 2 0 1 3 0 8 9 5 7 1 7 3 0 1 3 0 2 8 4 1 8 1 2 0 1 3 5 2 8 9 1 0 6 4 0 1 3 0 8 9 5 6 0 1

Fig . 1 9 .8 D a t a f ro m A u t h o r I S B N t a b le in B o o k s .

Relational Database Overview: Relational Database Overview: BooksBooks DatabaseDatabase

Fie ld Desc rip tion isbn ISBN number of the book (a string).

title Title of the book (a string). editionNumber Edition number of the book (a string). copyright Copyright year of the book (an int).

16

py g y ( )publisherID Publisher’s ID number (an int). 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 database are for example purposes only.]

Fig. 19.9 Titles tab le from Books.

Relational Database Overview: Relational Database Overview: BooksBooks DatabaseDatabase

i s b n t i t l e e d i t i o n -N u m b e r

p u b l i s h - e r I D

c o p y -r i g h t

i m a g e F i l e p r i c e

0 1 3 0 9 2 3 6 1 3 P y t h o n H o w t o P r o g r a m

1 1 2 0 0 2 p y t h o n . j p g $ 6 9 . 9 5

0 1 3 0 6 2 2 2 1 4 C # H o w t o P r o g r a m

1 1 2 0 0 2 c s h t p . j p g $ 6 9 . 9 5

0 1 3 0 3 4 1 5 1 7 J a v a H o w t o P r o g r a m

4 1 2 0 0 2 j h t p 4 . j p g $ 6 9 . 9 5

0 1 3 0 6 4 9 3 4 1 T h e C o m p l e t e J a v a T r a i n i n g C o u r s e

4 2 2 0 0 2 j a v a c t c 4 . j p g $ 1 0 9 . 9 5

0 1 3 0 8 9 5 6 0 1 A d v a n c e d J a v a 2 P l a t f o r m H o w t o P r o g r a m

1 1 2 0 0 2 a d v j h t p 1 . j p g $ 6 9 . 9 5

0 1 3 0 3 0 8 9 7 8 I n t e r n e t a n d W o r l d W i d e W e b H o w t o

2 1 2 0 0 2 i w 3 h t p 2 . j p g $ 6 9 . 9 5

Fig. 19.10 part 1

17

P r o g r a m

0 1 3 0 2 9 3 6 3 6 V i s u a l B a s i c . N E T H o w t o P r o g r a m

2 1 2 0 0 2 v b n e t . j p g $ 6 9 . 9 5

0 1 3 0 8 9 5 6 3 6 T h e C o m p l e t e C + + T r a i n i n g C o u r s e

3 2 2 0 0 1 c p p c t c 3 . j p g $ 1 0 9 . 9 5

0 1 3 0 8 9 5 5 1 2 T h e C o m p l e t e e -B u s i n e s s & e -C o m m e r c e P r o g r a m m i n g T r a i n i n g C o u r s e

1 2 2 0 0 1 e b e c c t c . j p g $ 1 0 9 . 9 5

0 1 3 0 8 9 5 6 1 X T h e C o m p l e t e I n t e r n e t & W o r l d W i d e W e b P r o g r a m m i n g T r a i n i n g C o u r s e

2 2 2 0 0 1 i w 3 c t c 2 . j p g $ 1 0 9 . 9 5

0 1 3 0 8 9 5 5 4 7 T h e C o m p l e t e P e r l T r a i n i n g C o u r s e

1 2 2 0 0 1 p e r l . j p g $ 1 0 9 . 9 5

0 1 3 0 8 9 5 5 6 3 T h e C o m p l e t e X M L P r o g r a m m i n g T r a i n i n g C o u r s e

1 2 2 0 0 1 x m l c t c . j p g $ 1 0 9 . 9 5

Relational Database Overview: Relational Database Overview: BooksBooks DatabaseDatabase

0 1 3 0 8 9 5 7 2 5 C H o w t o P r o g r a m 3 1 2 0 0 1 c h t p 3 . j p g $ 6 9 . 9 5

0 1 3 0 8 9 5 7 1 7 C + + H o w t o P r o g r a m

3 1 2 0 0 1 c p p h t p 3 . j p g $ 6 9 . 9 5

0 1 3 0 2 8 4 1 9 X e - B u s i n e s s a n d e -C o m m e r c e H o w t o P r o g r a m

1 1 2 0 0 1 e b e c h t p 1 . j p g $ 6 9 . 9 5

0 1 3 0 6 2 2 2 6 5 W i r e l e s s I n t e r n e t a n d M o b i l e B u s i n e s s H o w t o P r o g r a m

1 1 2 0 0 1 w i r e l e s s . j p g $ 6 9 . 9 5

0 1 3 0 2 8 4 1 8 1 P e r l H o w t o P r o g r a m

1 1 2 0 0 1 p e r l h t p 1 . j p g $ 6 9 . 9 5

Fig. 19.10 part 2

18

0 1 3 0 2 8 4 1 7 3 X M L H o w t o P r o g r a m

1 1 2 0 0 1 x m l h t p 1 . j p g $ 6 9 . 9 5

0 1 3 0 8 5 6 1 1 8 T h e C o m p l e t e I n t e r n e t a n d W o r l d W i d e W e b P r o g r a m m i n g T r a i n i n g C o u r s e

1 2 2 0 0 0 i w 3 c t c 1 . j p g $ 1 0 9 . 9 5

0 1 3 0 1 2 5 0 7 5 J a v a H o w t o P r o g r a m ( J a v a 2 )

3 1 2 0 0 0 j h t p 3 . j p g $ 6 9 . 9 5

0 1 3 0 8 5 2 4 8 1 T h e C o m p l e t e J a v a 2 T r a i n i n g C o u r s e

3 2 2 0 0 0 j a v a c t c 3 . j p g $ 1 0 9 . 9 5

0 1 3 0 3 2 3 6 4 0 e - B u s i n e s s a n d e -C o m m e r c e f o r M a n a g e r s

1 1 2 0 0 0 e b e c m . j p g $ 6 9 . 9 5

0 1 3 0 1 6 1 4 3 8 I n t e r n e t a n d W o r l d W i d e W e b H o w t o P r o g r a m

1 1 2 0 0 0 i w 3 h t p 1 . j p g $ 6 9 . 9 5

0 1 3 0 1 3 2 4 9 7 G e t t i n g S t a r t e d w i t h V i s u a l C + + 6 w i t h a n I n t r o d u c t i o n t o M F C

1 1 1 9 9 9 g s v c . j p g $ 4 9 . 9 5

Page 4: C# and Databases - City University of New York · 1 CSC 330 Object Oriented Programming C# and Databases Introduction Database: Integrated colle ction of data Database management

4

Relational Database Overview: Relational Database Overview: BooksBooks DatabaseDatabase

0 1 3 0 8 2 9 2 9 3 T h e C o m p le t e V is u a l B a s ic 6 T ra in in g C o u rs e

1 2 1 9 9 9 v b c t c 1 . j p g $ 1 0 9 .9 5

0 1 3 4 5 6 9 5 5 5 V is u a l B a s ic 6 H o w to P r o g r a m

1 1 1 9 9 9 v b h t p 1 . j p g $ 6 9 .9 5

0 1 3 2 7 1 9 7 4 6 J a v a M u lt im e d ia C yb er C la s s r o o m

1 2 1 9 9 8 j a v a c t c . j p g $ 1 0 9 .9 5

0 1 3 6 3 2 5 8 9 0 J a v a H o w to P ro g ra m

1 1 1 9 9 8 j h t p 1 . j p g $ 6 9 .9 5

0 1 3 9 1 6 3 0 5 0 T h e C o m p le t e C + + T ra in in g C o u rs e

2 2 1 9 9 8 c p p c t c 2 . j p g $ 1 0 9 .9 5

Fig. 19.10 part 3

19

0 1 3 5 2 8 9 1 0 6 C + + H o w t o P ro g ra m

2 1 1 9 9 8 c p p h t p 2 . j p g $ 4 9 .9 5

0 1 3 7 9 0 5 6 9 6 T h e C o m p le t e J a v a T ra in in g C o u rs e

2 2 1 9 9 8 j a v a c t c 2 . j p g $ 1 0 9 .9 5

0 1 3 0 8 2 9 2 7 7 T h e C o m p le t e J a v a T ra in in g C o u rs e (J a v a 1 .1 )

2 2 1 9 9 8 j a v a c t c 2 . j p g $ 9 9 .9 5

0 1 3 8 9 9 3 9 4 7 J a v a H o w to P ro g ra m (J a v a 1 .1 )

2 1 1 9 9 8 j h t p 2 . j p g $ 4 9 .9 5

0 1 3 1 1 7 3 3 4 0 C + + H o w t o P ro g ra m

1 1 1 9 9 4 c p p h t p 1 . j p g $ 6 9 .9 5

0 1 3 2 2 6 1 1 9 7 C H o w t o P r o g ra m 2 1 1 9 9 4 c h t p 2 . j p g $ 4 9 .9 5

0 1 3 1 1 8 0 4 3 6 C H o w t o P r o g ra m 1 1 1 9 9 2 c h t p . j p g $ 6 9 .9 5

Fig . 1 9 .1 0 D a t a f ro m t h e T i t l e s t a b le o f B o o k s .

The Books DatabaseThe Books Database

Entity-relationship diagram for the Book database

20

AuthorISBN

authorID

isbn

Authors

authorID

firstName

lastName

Publishers

publisherID

publisherName

Titles

isbn

titleeditionNumber

copyright

publisherIDimageFile

price

1

¥

¥

¥11

Relational Database QueriesRelational Database QueriesRelational Database QueriesRelational Database Queries

QueriesQueries : return a new result setBased upon relationalrelational algebraalgebra

Uses 3 operations to build a new relation

21

(a result-set)ProjectionProjection, selectionselection, and joinjoin

What is SQL?What is SQL?

Structured Query Language (SQLSQL)Keywords and rules used to implement relational algebra operations

22

SQL KeywordsSQL Keywords

SQL keyword Description SELECT Selects (retrieves) fields from one or more tables.

FROM Specifies tables from which to get fields or delete records. Required in every SELECT and DELETE statement.

WHERE Specifies criteria that determine the rows to be retrieved

23

WHERE Specifies criteria that determine the rows to be retrieved. INNER JOIN Joins records from multiple tables to produce a single set of records. GROUP BY Specifies criteria for grouping records. ORDER BY Specifies criteria for ordering records. INSERT Inserts data into a specified table. UPDATE Updates data in a specified table. DELETE Deletes data from a specified table.

Fig. 19.12 SQL query keywords.

Basic Select QueryBasic Select Query

Extracts information from one or more tables in a databaseFormat:

Basic: select * from tableselect * from table--namenameE l l t * f thl t * f th

24

Example: select * from authorsselect * from authors* means "extract all columns"

To get a projection (specific columns), use a list:select firstname, lastname from authorsselect firstname, lastname from authorsColumn, table names may be case sensitiveSQL keywords should not be case sensitive

Page 5: C# and Databases - City University of New York · 1 CSC 330 Object Oriented Programming C# and Databases Introduction Database: Integrated colle ction of data Database management

5

Basic Basic SelectSelect QueryQuery

authorID lastName authorID lastName 1 Deitel 8 M cPhie

2 Deitel 9 Yaeger

3 Nieto 10 Zlatkina

4 Steinbuhler 12 W iedermann

25

4 Steinbuhler 12 W iedermann

5 Santry 12 Liperi

6 Lin 13 Listfield 7 Sadhu

Fig . 19.13 authorID a n d lastName fro m th e Authors ta b le .

WhereWhere ClauseClause

Used to specify certain criteria in a queryBasic form:

SELECT * FROM tableName WHERE criteria

26

Example:SELECT * FROM Titles WHERE copyright > 1999

Can use LIKE clauseUsed for pattern matching

Uses wildcards*: zero or more characters take its place?: exactly one character takes its place

PatternPattern--matching with Wherematching with Where

Can use likelike clause for string pattern matchingUses wildcards

%: zero or more characters take its place (*)_: exactly one character takes its place (?)

27

_ y p ( )

Examples:Select * from authors where firstname like '_e%'Select * from authors where firstname like '_e%'Select * from authors where lastname like 'D%'Select * from authors where lastname like 'D%'

WHEREWHERE ClauseClauseT i t l e e d i t i o n N u m b e r c o p y r i g h t

I n t e r n e t a n d W o r l d W i d e W e b H o w to P r o g r a m 2 2 0 0 2

J a v a H o w t o P r o g r a m 4 2 0 0 2

T h e C o m p l e t e J a v a T r a i n i n g C o u r s e 4 2 0 0 2

T h e C o m p l e t e e - B u s i n e s s & e - C o m m e r c e P r o g r a m m i n g T r a i n i n g C o u r s e

1 2 0 0 1

T h e C o m p l e t e I n t e r n e t & W o r l d W i d e W e b P r o g r a m m i n g T r a i n in g C o u r s e

2 2 0 0 1

T h e C o m p l e t e P e r l T r a i n in g C o u r s e 1 2 0 0 1 T h e C o m p l e t e X M L P r o g r a m m i n g T r a i n i n g C o u r s e 1 2 0 0 1

C H o w t o P r o g r a m 3 2 0 0 1

C + + H o w to P r o g r a m 3 2 0 0 1

28

g

T h e C o m p l e t e C + + T r a i n i n g C o u r s e 3 2 0 0 1

e - B u s i n e s s a n d e - C o m m e r c e H o w t o P r o g r a m 1 2 0 0 1 I n t e r n e t a n d W o r l d W i d e W e b H o w to P r o g r a m 1 2 0 0 0

T h e C o m p l e t e I n t e r n e t a n d W o r l d W i d e W e b P r o g r a m m i n g T r a i n in g C o u r s e

1 2 0 0 0

J a v a H o w t o P r o g r a m ( J a v a 2 ) 3 2 0 0 0

T h e C o m p l e t e J a v a 2 T r a in i n g C o u r s e 3 2 0 0 0

X M L H o w t o P r o g r a m 1 2 0 0 1

P e r l H o w t o P r o g r a m 1 2 0 0 1

A d v a n c e d J a v a 2 P l a t f o r m H o w t o P r o g r a m 1 2 0 0 2 e - B u s i n e s s a n d e - C o m m e r c e f o r M a n a g e r s 1 2 0 0 0

W i r e l e s s I n t e r n e t a n d M o b i l e B u s i n e s s H o w t o P r o g r a m 1 2 0 0 1

C # H o w T o P r o g r a m 1 2 0 0 2

P y t h o n H o w t o P r o g r a m 1 2 0 0 2 V i s u a l B a s i c . N E T H o w to P r o g r a m 2 2 0 0 2

Fig . 1 9 . 1 4 Tit le s w i t h c o p y r ig h t s a f t e r 1 9 9 9 f r o m t a b le T i t l e s .

WHEREWHERE ClauseClause

authorID firstName lastName 1 Harvey Deitel

2 Paul Deitel Fig. 19.15 Authors from the Authors table whose last names start with D.

29

authorID firstName lastName 3 Tem Nieto

6 Ted Lin

11 Ben Wiedermann 12 Jonathan Liperi

13 Jeffrey Listfield

Fig. 19.16 Authors from table Authors whose last names contain i as the second letter.

Sorting the ResultsSorting the Results

SQL queries return their data in indeterminate orderSame query may return rows in different order each time

Use the order by clause to arrange results of a queryC b di ( ) d di (d ) d

30

Can be ascending (asc) or descending (desc) orderExamples:

select * from authors order by lastname descselect * from authors order by lastname descselect * from authors select * from authors

order by lastname, firstname ascorder by lastname, firstname asc

Page 6: C# and Databases - City University of New York · 1 CSC 330 Object Oriented Programming C# and Databases Introduction Database: Integrated colle ction of data Database management

6

ORDER BYORDER BY ClauseClause

Used to arrange results of a queryCan be ascending or descending order

Uses ASC and DESC respectively

Example:

31

Example:SELECT authorID FROM Authors ORDER BY authorID ASC

Can be used to sort by multiple fields

ORDER BYORDER BY ClauseClauseauthorID firstName lastName 2 Paul Deitel

1 Harvey Deitel

6 Ted Lin

12 Jonathan Liperi

13 Jeffrey Listfield

32

y8 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.

ORDER BYORDER BY ClauseClauseauthorID firstName lastName 10 Marina Zlatkina

9 Cheryl Yaeger

11 Ben Wiedermann

4 Kate Steinbuhler

5 Sean Santry

33

7 Praveen Sadhu 3 Tem Nieto

8 David McPhie

13 Jeffrey Listfield

12 Jonathan Liperi

6 Ted Lin 2 Paul Deitel

1 Harvey Deitel Fig. 19.18 Authors from table Authors in descending order by lastName.

ORDER BYORDER BY ClauseClauseauthorID firstName lastName 1 Harvey Deitel

2 Paul Deitel

6 Ted Lin

12 Jonathan Liperi

13 Jeffrey Listfield

8 David McPhie

34

8 David McPhie3 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.

ORDER BYORDER BY ClauseClausei s b n t i t l e e d i t i o n -

N u m b e r c o p y -r i g h t

p r i c e

0 1 3 0 8 9 5 6 0 1 A d v a n c e d J a v a 2 P l a t f o r m H o w t o P r o g r a m

1 2 0 0 2 $ 6 9 . 9 5

0 1 3 1 1 8 0 4 3 6 C H o w t o P r o g r a m 1 1 9 9 2 $ 6 9 . 9 5

0 1 3 0 8 9 5 7 2 5 C H o w t o P r o g r a m 3 2 0 0 1 $ 6 9 . 9 5

0 1 3 2 2 6 1 1 9 7 C H o w t o P r o g r a m 2 1 9 9 4 $ 4 9 . 9 5 0 1 3 0 6 2 2 2 1 4 C # H o w T o P r o g r a m 1 2 0 0 2 $ 6 9 . 9 5

0 1 3 5 2 8 9 1 0 6 C + + H o w to P r o g r a m 2 1 9 9 8 $ 4 9 . 9 5 0 1 3 1 1 7 3 3 4 0 C + + H o w to P r o g r a m 1 1 9 9 4 $ 6 9 . 9 5

0 1 3 0 8 9 5 7 1 7 C + + H o w to P r o g r a m 3 2 0 0 1 $ 6 9 . 9 5

0 1 3 0 2 8 4 1 9 X e - B u s i n e s s a n d e - C o m m e r c e 1 2 0 0 1 $ 6 9 . 9 5

35

0 1 3 0 2 8 4 1 9 X e B u s i n e s s a n d e C o m m e r c e H o w t o P r o g r a m

1 2 0 0 1 $ 6 9 . 9 5

0 1 3 0 3 0 8 9 7 8 I n t e r n e t a n d W o r l d W i d e W e b H o w t o P r o g r a m

2 2 0 0 2 $ 6 9 . 9 5

0 1 3 0 1 6 1 4 3 8 I n t e r n e t a n d W o r l d W i d e W e b H o w t o P r o g r a m

1 2 0 0 0 $ 6 9 . 9 5

0 1 3 0 3 4 1 5 1 7 J a v a H o w t o P r o g r a m 4 2 0 0 2 $ 6 9 . 9 5 0 1 3 6 3 2 5 8 9 0 J a v a H o w t o P r o g r a m 1 1 9 9 8 $ 4 9 . 9 5 0 1 3 0 2 8 4 1 8 1 P e r l H o w t o P r o g r a m 1 2 0 0 1 $ 6 9 . 9 5

0 1 3 0 9 2 3 6 1 3 P y t h o n H o w t o P r o g r a m 1 2 0 0 2 $ 6 9 . 9 5

0 1 3 0 2 9 3 6 3 6 V i s u a l B a s i c . N E T H o w t o P r o g r a m

2 2 0 0 2 $ 6 9 . 9 5

0 1 3 4 5 6 9 5 5 5 V i s u a l B a s i c 6 H o w t o P r o g r a m

1 1 9 9 9 $ 6 9 . 9 5

0 1 3 0 6 2 2 2 6 5 W i r e l e s s I n t e r n e t a n d M o b i l e B u s i n e s s H o w t o P r o g r a m

1 2 0 0 1 $ 6 9 . 9 5

0 1 3 0 2 8 4 1 7 3 X M L H o w t o P r o g r a m 1 2 0 0 1 $ 6 9 . 9 5

F ig . 1 9 . 2 0 B o o k s f r o m t a b le T i t l e s w h o se t it le s e n d w it h H o w t o P r o g r a m in a sc e n d in g o rd e r b y t i t l e .

Merging Data from Multiple Tables: Merging Data from Multiple Tables: INNER JOININNER JOIN

Merges records from multiple tables into a single recordTests for matching values in a common field

General Form:l t * f t bl 1 l t * f t bl 1

36

select * from table1 select * from table1 inner join table 2 on table1.field = table2.fieldinner join table 2 on table1.field = table2.field

Example:select firstname, isbn from select firstname, isbn from authors inner join authorISBNauthors inner join authorISBNon authors.authorID = authorsISBN.authorIDon authors.authorID = authorsISBN.authorID

Page 7: C# and Databases - City University of New York · 1 CSC 330 Object Oriented Programming C# and Databases Introduction Database: Integrated colle ction of data Database management

7

Merging Data from Multiple Tables: Merging Data from Multiple Tables: INNER JOININNER JOIN

fi r s t N a m e l a s t N a m e i s b n f i r s t N a m e l a s t N a m e i s b n H a r v e y D e i te l 0 1 3 0 8 9 5 6 0 1 H a r v e y D e i te l 0 1 3 0 8 2 9 2 9 3

H a r v e y D e i te l 0 1 3 0 2 8 4 1 8 1 H a r v e y D e i te l 0 1 3 4 5 6 9 5 5 5

H a r v e y D e i te l 0 1 3 0 2 8 4 1 7 3 H a r v e y D e i te l 0 1 3 0 8 2 9 2 7 7

H a r v e y D e i te l 0 1 3 0 8 5 2 4 7 3 P a u l D e i te l 0 1 3 0 1 2 5 0 7 5

H a r v e y D e i te l 0 1 3 8 9 9 3 9 4 7 P a u l D e i te l 0 1 3 0 8 5 6 1 1 8

H a r v e y D e i te l 0 1 3 0 8 5 6 1 1 8 P a u l D e i te l 0 1 3 0 1 6 1 4 3 8 H a r v e y D e i te l 0 1 3 0 1 6 1 4 3 8 P a u l D e i te l 0 1 3 0 2 8 4 1 9 x

H a r v e y D e i te l 0 1 3 0 2 8 4 1 9 x P a u l D e i te l 0 1 3 9 1 6 3 0 5 0

H a r v e y D e i te l 0 1 3 9 1 6 3 0 5 0 P a u l D e i te l 0 1 3 0 8 9 5 6 0 1

37

H a r v e y D e i te l 0 1 3 9 1 6 3 0 5 0 P a u l D e i te l 0 1 3 0 8 9 5 6 0 1

H a r v e y D e i te l 0 1 3 5 2 8 9 1 0 6 P a u l D e i te l 0 1 3 5 2 8 9 1 0 6 H a r v e y D e i te l 0 1 3 0 8 9 5 7 1 7 P a u l D e i te l 0 1 3 0 8 9 5 7 1 7

H a r v e y D e i te l 0 1 3 2 2 6 1 1 9 7 P a u l D e i te l 0 1 3 2 2 6 1 1 9 7

H a r v e y D e i te l 0 1 3 0 8 9 5 7 2 5 P a u l D e i te l 0 1 3 0 8 9 5 7 2 5

H a r v e y D e i te l 0 1 3 0 1 2 5 0 7 5 T e m N ie to 0 1 3 0 2 8 4 1 8 1

P a u l D e i te l 0 1 3 0 2 8 4 1 8 1 T e m N ie to 0 1 3 0 2 8 4 1 7 3

P a u l D e i te l 0 1 3 0 2 8 4 1 7 3 T e m N ie to 0 1 3 0 8 2 9 2 9 3

P a u l D e i te l 0 1 3 0 8 2 9 2 9 3 T e m N ie to 0 1 3 4 5 6 9 5 5 5

P a u l D e i te l 0 1 3 4 5 6 9 5 5 5 T e m N ie to 0 1 3 0 8 5 6 1 1 8

P a u l D e i te l 0 1 3 0 8 2 9 2 7 7 T e m N ie to 0 1 3 0 1 6 1 4 3 8

P a u l D e i te l 0 1 3 0 8 5 2 4 7 3 T e m N ie to 0 1 3 0 2 8 4 1 9 x

P a u l D e i te l 0 1 3 8 9 9 3 9 4 7

Fig . 1 9 .2 1 A u t h o rs f ro m t a b le A u t h o r s a n d ISBN n u m b e rs o f t h e a u t h o rs’ b o o k s, so rt e d in a sc e n d in g o rd e r b y l a s t N a m e a n d f i r s t N a m e .

Joining Data from Tables Authors, Joining Data from Tables Authors, AuthorISBN, Titles and PublishersAuthorISBN, Titles and Publishers

Tables produced by INNER JOIN can be used as arguments for another INNER JOIN

38

Joining Data from Tables Joining Data from Tables AuthorsAuthors, , AuthorISBNAuthorISBN, , TitlesTitles and and PublishersPublishers

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 ( A th INNER JOIN A th ISBN

Join Publishers and Titles tables if the publisherID matches

39

8 ( 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 Authors and AuthorISBN if authorID matches

Join two created tables if titlesISBN matches authorsISBN

Sort new table by title

Joining Data from Tables Joining Data from Tables AuthorsAuthors, , AuthorISBNAuthorISBN, , TitlesTitles and and PublishersPublishers

Titl e i s bn f i r s t -N a m e

l a s t -N a m e

c o py -r i gh t

p u b l i s he r -N a m e

A d v a n c e d Ja v a 2 P la tfo rm H o w to P ro g ra m

0 1 3 0 8 9 5 6 0 1 P a u l D e ite l 2 0 0 2 P re n tice H a ll

A d v a n c e d Ja v a 2 P la tfo rm H o w to P ro g ra m

0 1 3 0 8 9 5 6 0 1 H a rv e y D e ite l 2 0 0 2 P re n tice H a ll

A d v a n c e d Ja v a 2 P la tfo rm H o w to P ro g ra m

0 1 3 0 8 9 5 6 0 1 S e a n S a n try 2 0 0 2 P re n tice H a ll

C H o w to P ro g ra m 0 1 3 1 1 8 0 4 3 6 H a rv e y D e ite l 1 9 9 2 P re n tice H a ll

C H o w to P ro g ra m 0 1 3 1 1 8 0 4 3 6 P a u l D e ite l 1 9 9 2 P re n tice H a ll

Fig. 19.23 part 1

40

g

C H o w to P ro g ra m 0 1 3 2 2 6 1 1 9 7 H a rv e y D e ite l 1 9 9 4 P re n tice H a ll

C H o w to P ro g ra m 0 1 3 2 2 6 1 1 9 7 P a u l D e ite l 1 9 9 4 P re n tice H a ll

C H o w to P ro g ra m 0 1 3 0 8 9 5 7 2 5 H a rv e y D e ite l 2 0 0 1 P re n tice H a ll

C H o w to P ro g ra m 0 1 3 0 8 9 5 7 2 5 P a u l D e ite l 2 0 0 1 P re n tice H a ll

C # H o w T o P ro g ra m 0 1 3 0 6 2 2 2 1 4 T e m N ie to 2 0 0 2 P re n tice H a ll

C # H o w T o P ro g ra m 0 1 3 0 6 2 2 2 1 4 P a u l D e ite l 2 0 0 2 P re n tice H a ll

C # H o w T o P ro g ra m 0 1 3 0 6 2 2 2 1 4 J e ffr e y L is t fie ld 2 0 0 2 P re n tice H a ll

C # H o w T o P ro g ra m 0 1 3 0 6 2 2 2 1 4 C h e ryl Y a e g e r 2 0 0 2 P re n tice H a ll

C # H o w T o P ro g ra m 0 1 3 0 6 2 2 2 1 4 M a rin a Z la tk in a 2 0 0 2 P re n tice H a ll

C # H o w T o P ro g ra m 0 1 3 0 6 2 2 2 1 4 H a rv e y D e ite l 2 0 0 2 P re n tice H a ll

C + + H o w to P ro g ra m 0 1 3 0 8 9 5 7 1 7 P a u l D e ite l 2 0 0 1 P re n tice H a ll

Joining Data from Tables Joining Data from Tables AuthorsAuthors, , AuthorISBNAuthorISBN, , TitlesTitles and and PublishersPublishers

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

e-Business and e-Commerce for Managers

0130323640 Harvey Deitel 2000 Prentice Hall

B i d C 0130323640 K t St i b hl 2000 P ti H ll

Fig. 19.23 part 2

41

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 Po rt io n o f the re su lt se t p ro d uc e d b y the q ue ry in Fig . 19.22.

The Selection OperationThe Selection Operation

The selection operation is accomplished using wherewhereBasic form:

select * from tableselect * from table--name where criterianame where criteria

42

Example:select * from titles where copyright > 1999select * from titles where copyright > 1999

Make sure String criteria are inside single quotesCan use expected relational operators

select * from authors where firstname > 'B'select * from authors where firstname > 'B'

Page 8: C# and Databases - City University of New York · 1 CSC 330 Object Oriented Programming C# and Databases Introduction Database: Integrated colle ction of data Database management

8

Insert StatementInsert Statement

Inserts a new record into a tableGeneral form:

insert into tableinsert into table--name(fieldname1, fieldname2,...) name(fieldname1, fieldname2,...) l ( l 1 l 2)l ( l 1 l 2)

43

values(value1, value2)values(value1, value2)Example:

insert into authors(authorID, lastname, firstname)insert into authors(authorID, lastname, firstname)values(15, 'Gilbert', 'Steve')values(15, 'Gilbert', 'Steve')

Values must match field names in order and type

INSERTINSERT StatementStatementauthorID firstName lastName 1 Harvey Deitel

2 Paul Deitel

3 Tem Nieto

4 Kate Steinbuhler

5 Sean Santry

6 Ted Lin

44

7 Praveen Sadhu

8 David McPhie

9 Cheryl Yaeger

10 Marina Zlatkina 11 Ben Wiedermann

12 Jonathan Liperi

13 Jeffrey Listfield

14 Sue Smith

Fig. 19.24 Authors a fte r a n INSERT op era tion to a d d a rec ord .

The Update StatementThe Update Statement

Modifies data in a tableGeneral Form:

update tableupdate table--name set field1=value1 name set field1=value1 h it ih it i

45

where criteriawhere criteriaExample:

update authors set firstname='Stephen' update authors set firstname='Stephen' where lastname='Gilbert' and firstname='Steve'where lastname='Gilbert' and firstname='Steve'

What happens if you violate an integrity rule?

UPDATEUPDATE StatementStatementauthorID firstName lastName 1 Harvey Deitel

2 Paul Deitel

3 Tem Nieto

4 Kate Steinbuhler

5 Sean Santry

6 Ted Lin

46

6 Ted Lin 7 Praveen Sadhu

8 David McPhie

9 Cheryl Yaeger

10 Marina Zlatkina

11 Ben Wiedermann 12 Jonathan Liperi

13 Jeffrey Listfield

14 Sue Jones

Fig. 19.25 Ta b le Authors a fte r a n UPDATE op era tion to c ha nge a rec ord .

The Delete StatementThe Delete Statement

Removes data from a tableGeneral Form:

delete from tabledelete from table--name where criterianame where criteriaD 't f t th it i !!!

47

Don't forget the criteria!!!Example:

delete from authors where lastname='Gilbert'delete from authors where lastname='Gilbert'

DELETEDELETE StatementStatementauthorID firstName lastName 1 Harvey Deitel

2 Paul Deitel 3 Tem Nieto

4 Kate Steinbuhler

5 Sean Santry

6 T d Li

48

6 Ted Lin 7 Praveen Sadhu

8 David McPhie 9 Cheryl Yaeger

10 Marina Zlatkina

11 Ben Wiedermann 12 Jonathan Liperi

13 Jeffrey Listfield

Fig. 19.26 Table Authors after a DELETE operation to remove a record .

Page 9: C# and Databases - City University of New York · 1 CSC 330 Object Oriented Programming C# and Databases Introduction Database: Integrated colle ction of data Database management

9

Programming with ADO .NET: Programming with ADO .NET: Extracting Information from a DBMSExtracting Information from a DBMS

Examples that demonstrate how to connect to a database, query the database and display the results

f

49

of the query

Displaying a Database Table in a DataGridViewDisplaying a Database Table in a DataGridView

Step 1: Creating the ProjectStep 2: Adding a Data Source to the ProjectStep 3: Choosing the Data Source Type to Add to the

50

ProjectStep 4: Adding a New Database ConnectionStep 5: Choosing the Books.mdf Data ConnectionStep 6: Saving the Connection String

Step 1: Creating the ProjectStep 1: Creating the ProjectCreate a new Windows Application named Create a new Windows Application named DisplayTableDisplayTable. Change the Form name to . Change the Form name to DisplayTableFormDisplayTableForm

and change the source file name to and change the source file name to DisplayTable.csDisplayTable.cs. Then set the Form's Text property to Display Table.. Then set the Form's Text property to Display Table.

51

Step 2: Adding a Data Source to the ProjectStep 2: Adding a Data Source to the Project

To interact with a data source (e.g., a database), you must add it to the project using the Data Sources window, which lists the data that your project can access. Open the Data Sources window by selecting Data > Show Data Sources or b li ki th t b t th i ht f th t b f th S l ti

52

by clicking the tab to the right of the tab for the Solution Explorer. In the Data Sources window, click Add New Data Source... to open the Data Source Configuration Wizard. This wizard guides you through connecting to a database and choosing the parts of the database you will want to access in your project.

Step 2: Adding a Data Source to the ProjectStep 2: Adding a Data Source to the Project

53

Step Step 3: Choosing the Data Source Type to Add to the 3: Choosing the Data Source Type to Add to the ProjectProject

The first screen of the Data Source Configuration Wizard asks you to choose the data source type you wish to include in the project. Select Database and click Next >

54

Next >.

Page 10: C# and Databases - City University of New York · 1 CSC 330 Object Oriented Programming C# and Databases Introduction Database: Integrated colle ction of data Database management

10

Step 4: Adding a New Database ConnectionStep 4: Adding a New Database Connection

You must next choose the connection that will be used to connect to the database (i.e., the actual source of the data). Click New Connection... to open the Add Connection dialog. If the Data Source is not set to Microsoft SQL Server D t b Fil (S lCli t) li k Ch l t Mi ft

55

Database File (SqlClient), click Change..., select Microsoft SQL Server Database File and click OK. In the Add Connection dialog, click Browse..., locate the Books.mdf database file on your computer, select it and click Open. You can click Test Connection to verify that the IDE can connect to the database through SQL Server. Click OK to create the connection.

Step 4: Adding a New Database ConnectionStep 4: Adding a New Database Connection

56

Step 5: Choosing the Books.mdf Data ConnectionStep 5: Choosing the Books.mdf Data Connection

Now that you have created a connection to the Books.mdf database, you can select and use this connection to access the database. Click Next > to set the connection then click Yes when asked whether you

57

the connection, then click Yes when asked whether you want to move the database file to your project.

Step 5: Choosing the Books.mdf Data ConnectionStep 5: Choosing the Books.mdf Data Connection

58

Step 6: Saving the Connection StringStep 6: Saving the Connection String

The next screen asks you whether you want to save the connection string to the application configuration file. A connection string specifies the path to a database file on disk, as well as some additional settings that determine how t th d t b S i th ti t i i

59

to access the database. Saving the connection string in a configuration file makes it easy to change the connection settings at a later time. Leave the default selections and click Next > to proceed.

Step 6: Saving the Connection StringStep 6: Saving the Connection String

60

Page 11: C# and Databases - City University of New York · 1 CSC 330 Object Oriented Programming C# and Databases Introduction Database: Integrated colle ction of data Database management

11

Displaying a Database Table in a DataGridView cont’dDisplaying a Database Table in a DataGridView cont’d

Step 7: Selecting the Database Objects to Include in Your DatasetStep 8: Viewing the Data Source in the Data Sources Wi d

61

WindowStep 9: Viewing the Database in the Solution Explorer

Step 7: Selecting the Database Objects to Include in Step 7: Selecting the Database Objects to Include in Your Your DataSetDataSet

The IDE retrieves information about the database you selected and prompts you to select the database objects (i.e., the parts of the database) that you want your project to be able to access. Recall that programs typically access a database's contents through a cache of the data, which is stored in a DataSet. In response to your selections in this screen, the IDE will generate a class derived from System.Data.DataSet that is designed specifically to store data from the Books

62

database. Click the checkbox to the left of Tables to indicate that the custom DataSetshould cache (i.e., locally store) the data from all the tables in the Books databaseAuthors, AuthorISBN and Titles. By default, the IDE names the DataSetBooksDataSet, though it is possible to specify a different name in this screen. Finally, click Finish to complete the process of adding a data source to the project.

Step 7: Selecting the Database Objects to Step 7: Selecting the Database Objects to Include in Your Include in Your DataSetDataSet

63

Step 8: Viewing the Data Source in the Data Step 8: Viewing the Data Source in the Data Sources WindowSources Window

Notice that a BooksDataSet node now appears in the Data Sources window with child nodes for each table in the Books databasethese nodes represent the DataTables of the BooksDataSet Expand the

64

the DataTables of the BooksDataSet. Expand the Authors node and you will see the table's columnsthe DataSet's structure mimics that of the actual Books database

Step 8: Viewing the Data Source in the Step 8: Viewing the Data Source in the Data Sources WindowData Sources Window

65

Step 9: Viewing the Database in the Solution Step 9: Viewing the Database in the Solution ExplorerExplorer

Books.mdf is now listed as a node in the Solution Explorer, indicating that the database is now part of this project. In addition, the Solution Explorer now lists a new node named BooksDataSet.xsd. A file with the .xsd extension is an XML Schema document, which specifies the structure of a set of XML documents. The IDE uses an XML Schema

66

document to represent a DataSet's structure, including the tables that comprise the DataSet and the relationships among them. When you added the Books database as a data source, the IDE created the BooksDataSet.xsd file based on the structure of the Books database. The IDE then generated class BooksDataSet from the schema (i.e., structure) described by the .xsd file.

Page 12: C# and Databases - City University of New York · 1 CSC 330 Object Oriented Programming C# and Databases Introduction Database: Integrated colle ction of data Database management

12

Step 9: Viewing the Database in the Step 9: Viewing the Database in the Solution ExplorerSolution Explorer

67

Displaying the Authors TableDisplaying the Authors Table

Now that you have added the Books database as a data source, you can display the data from the database's Authors table in your program. The IDE provides design tools that allow you to display data from a data source on a Form without writing any code. Simply drag and drop items from the Data Sources window onto a Form, and the IDE generates the GUI controls and code necessary to display the selected data source's content.

To display the Authors table of the Books database drag the Authors node from the Data Sources

68

To display the Authors table of the Books database, drag the Authors node from the Data Sources window to the Form. The IDE generates two GUI controls that appear on DisplayTableFormauthorsBindingNavigator and authorsDataGridView. The IDE also generates several additional non-visual components that appear in the component traythe gray region below the Form in Design view. We use the IDE's default names for these autogenerated components (and others throughout the chapter) to show exactly what the IDE creates. We briefly discuss the authorsBindingNavigator and authorsDataGridView controls here. The next section discusses all of the autogenerated components in detail and explains how the IDE uses these components to connect the GUI controls to the Authors table of the Books database.

Design view after dragging the Authors data source node to the FormDesign view after dragging the Authors data source node to the Form

69

Displaying the Authors table in a Displaying the Authors table in a DataGridViewDataGridView

A DataGridView displays data organized in rows and columns that correspond to the rows and columns of the underlying data source. In this case, the DataGridViewdisplays the data of the Authors table, so the control has

l d A th ID Fi tN d L tN I

70

columns named AuthorID, FirstName and LastName. In Design view, the control does not display any rows of actual data below the column headers. The data is retrieved from the database and displayed in the DataGridView only at runtime. Execute the program. When the Form loads, the DataGridView contains four rows of dataone for each row of the Authors table

Displaying the Authors table in a Displaying the Authors table in a DataGridViewDataGridView

71

Binding NavigatorBinding Navigator

The strip of buttons below the title bar of the window is a BindingNavigator, which enables users to browse and manipulate data displayed by another GUI control (in this case, a DataGridView) on the Form. A BindingNavigator's buttons resemble the controls on a CD or DVD player and allow you to move to the first row of data, the preceding row, the next row and the last row. The control also displays the currently selected row number in a text box. You can use this text box to enter the number of a row that you want to select. The authorsBindingNavigator in this example allows you to "navigate" the Authors table displayed in the authorsDataGridView. Clicking the buttons or entering a value in the text box causes the DataGridView to select th i t A i th D t G idVi ' l ft t l i di t th tl l t d

72

the appropriate row. An arrow in the DataGridView's leftmost column indicates the currently selected row.A BindingNavigator also has buttons that allow you to add a new row, delete a row and save changes back to the underlying data source (in this case, the Authors table of the Books database). Clicking the button with the yellow plus icon () adds a new row to the DataGridView. However, simply typing values in the FirstName and LastName columns does not insert a new row in the Authors table. To add the new row to the database on disk, click the Save button (the button with the disk icon, ). Clicking the button with the red X () deletes the currently selected row from the DataGridView. Again, you must click the Save button to make the change in the database. Test these buttons. Execute the program and add a new row, then save the changes and close the program. When you restart the program, you should see that the new row was saved to the database and appears in the DataGridView. Now delete the new row and click the Save button. Close and restart the program to see that the new row no longer exists in the database.

Page 13: C# and Databases - City University of New York · 1 CSC 330 Object Oriented Programming C# and Databases Introduction Database: Integrated colle ction of data Database management

13

Querying the Books DatabaseQuerying the Books Database

Step 1: Creating the ProjectStep 2: Adding a Data Source to the ProjectStep 3: Creating a DataGridView to Display the Titles

73

TableStep 4: Adding Custom Queries to the TitlesTableAdaptorStep 5: Choosing How the TableAdapter Schould Access the Database

Querying the Books Database cont’dQuerying the Books Database cont’d

Step 6: Choosing the Query RypeStep 7: Specifying a SELECT Statement for the QueryStep 8: Building a Query with Query Builder

74

Step 9: Closing the Query BuilderStep 10: Setting the Names of the Autogenerated Methods That Perform the QueryStep 11: Adding an Additional Query

Querying the Books Database cont’dQuerying the Books Database cont’d

Step 12: Adding a ComboBox to the Step 13: Customizing the Form’s Load Event Handler

75

Step 14: Programming an Event Handler for the ComboBox