Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 10- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.

Similar presentations


Presentation on theme: "Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 10- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis."— Presentation transcript:

1 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis Haywood Community College Kip Irvine Florida International University

2 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter Working With Databases 10

3 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Introduction Basic database terminology Fundamental database concepts Use ADO.NET to access databases Display, sort, and update database data Use the DataGridView control

4 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Database Management Systems 10.1 Visual Basic applications use database management systems to make large amounts of data available to programs

5 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Visual Basic and Database Management Systems Simple text files as shown in chapter 9 are: Fine for small amounts of data But impractical for large amounts of data Businesses must maintain huge amounts of data A database management system (DBMS) is the typical solution to the data needs of business Designed to store, retrieve, & manipulate data Visual Basic can communicate with a DBMS Tells DBMS what data to retrieve or manipulate Slide 10- 5

6 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Layered Approach to Using a DBMS Applications that work with a DBMS use a layered approach VB application is topmost layer VB sends instructions to next layer, the DBMS DBMS works directly with data Programmer need not understand the physical structure of the data Just need to know how to interact with the database Slide 10- 6

7 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Visual Basic Supports Many DBMSs Visual Basic can interact with many DBMSs Microsoft SQL Server Oracle DB2 MySQL Microsoft SQL Server 2008 Express used in this chapter Slide 10- 7

8 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Database Concepts 10.2 A database is a collection of one or more tables, each containing data related to a particular topic

9 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Terminology Database: a collection of interrelated tables Table: a logical grouping of related data A category of people, places, or things For example, employees or departments Organized into rows and columns Field: an individual piece of data pertaining to an item, an employee name for instance Record: the complete data about a single item such as all information about an employee A record is a row of a table

10 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Emp_IdFirst_NameLast_NameDepartment IgnacioFletaAccounting ChristianMartinComputer Support OrvilleGibsonHuman Resources BenSmithAccounting AllisonChongComputer Support Slide Database Table Row (Record) ColumnField Each table has a primary key Uniquely identifies that row of the table Emp_Id is the primary key in this example Columns are also called fields or attributes Each column has a particular data type

11 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide VB and SQL Server Data Types VB data types must match table data types SQL Server and VB have similar data types SQL TypeUsageVisual Basic Type BitTrue/false valuesBoolean DateTimeDates and timesDate, DateTime Decimal, MoneyFinancial valuesDecimal FloatReal-number valuesDouble IntInteger valuesInteger SmallintIntegers -32,768 to 32,767Short Varchar(n)Variable length stringsString TextStrings more than 8000 charString

12 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Choosing Column Names Define a column for each piece of data Allow plenty of space for text fields Avoid using spaces in column names For the members of an organization: Column NameTypeRemarks Member_IDintPrimary key First_Namevarchar(40) Last_Namevarchar(40) Phonevarchar(30) varchar(50) Date_JoinedsmalldatetimeDate only, no time values Meeings_Attendedsmallint OfficerYes/NoTrue/False values

13 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Issues with Redundant Data Database design minimizes redundant data In the following employee table: IDFirst_NameLast_NameDepartment IgnacioFletaAccounting ChristianMartinComputer Support OrvilleGibsonHuman Resources 00300JoseRamirezResearch & Devel BenSmithAccounting AllisonChongComputer Support Same dept name appears multiple times Requires additional storage space Causes problems if misspelled What if a department needs to be renamed?

14 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Eliminating Redundant Data Create a department table Dept_IDDept_NameNum_Employees 1Human Resources10 2Accounting5 3Computer Support30 4Research & Development15 Reference department table in employee table IDFirst_NameLast_NameDept_ID IgnacioFleta ChristianMartin OrvilleGibson JoseRamirez BenSmith AllisonChong3

15 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide One-to-Many Relationships The previous changes created a one-to-many relationship Every employee has one and only one dept Every department has many employees DeptID in department table is a primary key DeptID in employee table is a foreign key One-to-many relationship exists when primary key of one table is specified as a field of another table

16 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley DataGridView Control 10.3 The DataGridView Control Allows you to Display a Database Table in a Grid Which Can be Used at Runtime to Sort and Edit the Contents of the Table

17 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Connecting VB to a Database VB provides tools to display database tables Data binding links tables to controls on forms Controls called components establish the link A wizard guides you through the process Well use these data-related components: Data source – usually a database Binding source – connects data bound controls to a dataset Table adapter – uses SQL to select data Dataset – in-memory copy of data from tables

18 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Connecting VB to a Database The flow of data from database to application Data travels from data source to application Application can view/change dataset contents Changes to dataset can be written back to the data source Tutorial 10-1 demonstrates how to connect a database table to a DataGridView control

19 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data-Bound Controls 10.4 Some Controls Can Be Bound to a Dataset. A Data-bound Control Can be Used to Display and Edit the Contents of a Particular Row and Column

20 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Advantages of Data-Binding Can bind fields in a data source to controls: Text boxes Labels List boxes Contents of data-bound controls change automatically when moving from row to row Data-bound control also allow the contents of a database field to be changed

21 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Adding a New Data Source Open the Data Sources window Click the Add New Data Source link Follow the steps in the Data Source Configuration Wizard to create a connection to the database Slide

22 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Deleting a Data Source Once created, its almost impossible to rename a data source Easier to delete and create a new data source than rename one A data source named Employees for example would be defined by a file named Employees.xsd To delete this data source: Select Employees.xsd file in Solution Explorer Press Delete Slide

23 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Binding Existing Dataset to DataGrid If you wish to bind a dataset already found in the Data Sources window Locate the table in the Data Sources window Drag table to an open area of a form Creates a data grid bound to the data source Automatically adds a navigation bar to form Set Dock property to Center Docking to make the data grid fill the entire form

24 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Binding Individual Fields to Controls Use the dataset in the Data Sources window Select Details from the table drop-down list Drag table to an open area of a form Creates a separate control for each field Can also drag columns individually Text and numeric fields added as text boxes Yes/No fields added as checkboxes DateTime fields use DateTimePicker controls May wish to change some control properties Tutorial 10-3 & 10-4 demonstrate binding

25 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Binding to List and Combo Boxes List and combo boxes are frequently used to supply a list of items for a user to select from Such lists are often populated from a table Must set two list/combo box properties DataSource identifies a table within a dataset DisplayMember identifes the table column to be displayed in the list/combo box If table column dragged onto a list/combo box Visual Studio creates the required dataset, table adapter, and binding source components Tutorial 10-5 demonstrates binding to a list box

26 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Adding Rows to a Database Table A data source has a schema definition file (.xsd) An.xsd file was created in Tutorial 10-5 for the Members table DataTable created when data source added TableAdapter object created for the DataTable A TableAdapter object has an Insert method Used to add a new row to the database table Each column is an argument of the method Just provide the values for each argument MembersTableAdapter.Insert(10, Hasegawa, _ Adrian, , #5/15/2008#)

27 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Identity Columns Some database tables have an identity column Assigned a unique number by the database Occurs automatically for identity columns Thus no need to supply a value for this column Payments table uses an identity column So omit ID column value Supply Member_Id, Payment_Date, & Amount Tutorial 10-6 adds a row to the Payments table Slide PaymentsTableAdapter.Insert(5, #5/15/2008#, 50D)

28 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Reading Dataset Rows with For-Each A For-Each statement can be used to iterate over all rows of a dataset Usually use a strongly typed dataset for this Sum Amount column of dsPayments dataset Dim row as PaymentsDataSet.PaymentsRow Dim decTotal as Decimal = 0 For Each row in Me.PaymentsDataSet.Payments.Rows decTotal += row.Amount Next Tutorial 10-7 demonstrates this technique

29 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Structured Query Language (SQL) 10.5 SQL Is a Standard Language for Working With Databases

30 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide The Select Statement Select retrieves rows from one or more tables in a database Basic form of Select for a single table is Select column-list From table column-list contains column names to select from table, each separated by a comma The following Select statement retrieves the ID and Salary fields from the SalesStaff table Select ID, Salary From SalesStaff

31 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Column Names Use asterisk to select all columns in a table Select * From SalesStaff Unlike VB names, SQL columns can have embedded spaces If so, use square brackets around column names Select [Last Name], [First Name] From SalesStaff Better to avoid embedded spaces for this reason As operator can be used to rename columns Select Last_Name, Hire_Date As Date_Hired From Employees

32 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Creating New Columns Sometimes useful to create a new column by appending existing columns together Create a Full_Name field from first and last name Select Last_Name +, + First_Name as Full_Name From Members Creates a Full_Name field in the format last, first Can also be useful to create a new column by performing arithmetic operations Columns involved must be numeric Select ID, hrsWorked * hourlyRate As payAmount From Payroll Creates a payAmount column with gross pay

33 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Sorting Rows with Order By Clause SQL Select has an optional Order By clause that affects the order in which rows appear Order by Last_Name, First_Name Displays rows in order by last name, then first Sort in reverse order (high to low) using Desc Order by Last_Name DESC Order By clause appears after From clause Select First_Name, Last_Name, Date_Joined From Members Order By Last_Name, First_Name Lists all members by last name, then first

34 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Selecting Rows with Where Clause SQL Select has an optional Where clause that can be used to select (or filter) certain rows Where Last_Name = Gomez Displays only rows where last name is Gomez Must be a defined column (in table or created) This example selects based on a created field Select Last_Name, hrsWorked * Rate As payAmount From Payroll Where payAmount > 1000 Order by Last_Name Selects those being paid more than $1,000

35 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide SQL Relational Operators SQL Where uses relational operators just like a VB If OperatorMeaning =equal to <>not equal to greater than >=greater than or equal to Betweenbetween two values (inclusive) Likesimilar to (match using wildcard) Example of Between operator: Where Hire_Date Between #1/1/1992# and #12/31/1999# Example of Like operator with % sign as wildcard: Where Last_Name Like A%

36 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Compound Expressions SQL uses And, Or, and Not to create compound expressions Select all employees hired after 1/1/1990 and with a salary is greater than $40,000 Where (Hire_Date > #1/1/1990#) and (Salary > 40000) Select all employees hired after 1/1/1990 or with a salary is greater than $40,000 Where (Hire_Date > #1/1/1990#) or (Salary > 40000) Select employee names not beginning with A Where Last_Name Not Like A%

37 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Modifying a Query in a Data Source Dataset schema file contains an SQL query Created as part of schema file Named Fill, GetData() by default Right-click title bar of TableAdapter in schema Click Configure from pop-up Use Configuration Wizard to change simple queries Query Builder often used for complex queries Slide

38 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Query Builder Visual Studio tool to work with SQL queries Consists of 4 sections or panes Diagram pane displays tables Grid pane displays query in spreadsheet form SQL pane shows actual SQL created Results pane shows data returned by query Slide

39 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Adding a Query to a DataGridView Can add a new query as well as changing an existing one Right-click table adapter icon in component tray Select Add Query to display Search Criteria Builder Add Where clause Click New query name radio button enter a name for query Query made available from ToolStrip control Slide

40 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Karate School Management Application 10.6 Create an Application that Works With the Karate School Database

41 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Karate School Startup Form Slide Menu Selections: File Exit Membership List All Find member Add new member Payments All members One member

42 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Karate School Member Forms Slide All Members Form Add New Member Form Find Member by Last Name Form

43 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Karate School Payments Forms Slide Payments by All Members Form Payments by One Member Form


Download ppt "Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 10- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis."

Similar presentations


Ads by Google