Chapter 10 Accessing Database Files Programming In Visual Basic.NET.

Slides:



Advertisements
Similar presentations
Data Base. Objective Become familiar with database terminology. Create a project to display data for a single database table. Use a DataGrid control.
Advertisements

Chapter 10 Database Applications Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
 Open the Paradise.exe file  Application displays records in the Books database  Allows the store manager to enter an author’s name (or part of a name)
Chapter 14.3 LINQ to SQL Programming in Visual Basic 2010: The Very Beginner’s Guide by Jim McKeown Databases – Part 3.
Chapter 18 - Data sources and datasets 1 Outline How to create a data source How to use a data source How to use Query Builder to build a simple query.
Chapter 12: Using ADO.NET 2.0 Programming with Microsoft Visual Basic 2005, Third Edition.
Guide to Oracle10G1 Introduction To Forms Builder Chapter 5.
VB.NET Database Access ISYS546. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
Chapter 12: ADO.NET and ASP.NET Programming with Microsoft Visual Basic.NET, Second Edition.
Using ADO.NET Chapter Microsoft Visual Basic.NET: Reloaded 1.
A Guide to Oracle9i1 Introduction To Forms Builder Chapter 5.
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS 512.
VB.NET Database Access ISYS 812. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
1 Pertemuan 09 Database Matakuliah: D0524 / Algoritma dan Pemrograman Komputer Tahun: 2005 Versi:
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS 512.
Microsoft Visual Basic 2012 CHAPTER TEN Incorporating Databases with ADO.NET.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Chapter 14: Advanced Topics: DBMS, SQL, and ASP.NET
From VS C# 2010 Programming, John Allwork 1 VS2010 C# Programming - DB intro 1 Topics – Database Relational - linked tables SQL ADO.NET objects Referencing.
Some Basic Database Terminology
Chapter 10 - VB.Net by Schneider1 Chapter 10 – Database Management 10.1 An Introduction to Databases 10.2 Relational Databases and SQL.
Databases and LINQ Visual Basic 2010 How to Program 1.
Programming with Microsoft Visual Basic 2012 Chapter 13: Working with Access Databases and LINQ.
Chapter 11 Introduction to Database Processing. Class 11: Database Processing Use a Visual Studio Wizard to establish a database connection used to load.
Programming with Visual Basic.NET An Object-Oriented Approach  Chapter 8 Introduction to Database Processing.
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
Introduction to ADO.Net and Visual Studio Database Tools ISYS 512.
1 Lesson 6 — Database Programming Microsoft Visual Basic.NET, Introduction to Programming.
Irwin/McGraw-Hill Copyright© 2000 by the McGraw-Hill Companies, Inc. PowerPoint® Presentation to accompany prepared by James T. Perry University of San.
Chapter 10 Accessing Database Files Programming In Visual Basic.NET.
10-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
McGraw-Hill/Irwin Programming in Visual Basic 6.0 © 2002 The McGraw-Hill Companies, Inc. All rights reserved. Update Edition Chapter 11 Accessing Database.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Twelve Access Databases and LINQ.
Needs for Accessing Database To make your web site more dynamic and maintainable, you can display information on your web pages that are retrieved from.
CHAPTER EIGHT Accessing Data Processing Databases.
1 Data Bound Controls II Chapter Objectives You will be able to Use a Data Source control to get data from a SQL database and make it available.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Thirteen Working with Access Databases and LINQ.
CHAPTER EIGHT Accessing Data Processing Databases.
Chapter Thirteen Working with Access Databases and LINQ Programming with Microsoft Visual Basic th Edition.
Tutorial 91 Databases A database is an organized collection of related information stored in a file on a disk A database allows companies to store information.
Chapter Thirteen Working with Access Databases and LINQ Programming with Microsoft Visual Basic th Edition.
CSCI 3327 Visual Basic Chapter 13: Databases and LINQ UTPA – Fall 2011.
1 Chapter 20 – Data sources and datasets Outline How to create a data source How to use a data source How to use Query Builder to build a simple query.
Introduction to ADO.Net and VS Database Tools and Data Binding ISYS 350.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 25.1 Test-Driving the ATM Application 25.2.
Chapter Fourteen Access Databases and SQL Programming with Microsoft Visual Basic th Edition.
Databases and ADO.NET Programming Right from the Start with Visual Basic.NET 1/e 11.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 25 I’m Suffering from Information Overload.
1 Chapter 10 – Database Management 10.1 An Introduction to Databases 10.2 Editing and Designing Databases.
Chapter 24 I’m Suffering from Information Overload (Access Databases) Clearly Visual Basic: Programming with Visual Basic nd Edition.
1 Database Programming with ADO.NET Kashef Mughal.
ADO.NET Objects Data Adapters Dr. Ron Eaglin. Agenda Builds on Information in Part I Should have working knowledge of creating a database connection Continuation.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Address Book Application Introducing Database Programming.
Introduction to ADO.Net and Visual Studio Database Tools ISYS 350.
CSCI 3327 Visual Basic Chapter 13: Databases and LINQ UTPA – Fall 2011.
Chapter Fourteen Access Databases and SQL Programming with Microsoft Visual Basic th Edition.
Programming with Microsoft Visual Basic 2012 Chapter 14: Access Databases and SQL.
Programming with Microsoft Visual Basic 2012 Chapter 13: Working with Access Databases and LINQ.
Microsoft Visual Basic 2010: Reloaded Fourth Edition
Visual Basic 2010 How to Program
Incorporating Databases with ADO.NET
Incorporating Databases with ADO.NET
VB.NET Using Database.
Brief description on how to navigate within this presentation (ppt)
CIS16 Application Programming with Visual Basic
Chapter 10 ADO.
Database Applications
Chapter 10 Accessing Database Files
Introduction to ADO.Net and Visual Studio Database Tools.
Presentation transcript:

Chapter 10 Accessing Database Files Programming In Visual Basic.NET

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Visual Basic and Databases VB projects can display and update the data from database files VB.NET uses ADO.NET for database access ADO.NET is the next generation of database technology, based on Microsoft's previous version ActiveX Data Objects (ADO)

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved ADO.NET Data is stored and transferred in Extensible Markup Language (XML) Allows access to database data in many formats Two types of Connections –SQLClient for SQL Server –OLEDB for all other database formats

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Relational Database Terminology Database includes –Tables => collection of related data –Queries => SQL designed to select data from tables Table –Record => row of related data for one instance –Field => column of specific data element –Keys Primary => uniquely identifies a record Foreign => links record to related record in related table Relationships

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Using ADO.NET and VB Can display data from a database on –Windows Form –Web Form Add controls to form and bind data to them –Normal Controls like label, textbox –Special controls designed just for data like DataGrid, DataList

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Steps for Data Access Data Source Connection Data Adapter Dataset Web Form Windows Form Specific file OleDbConnection Object Handles data transfer and provides data for dataset; uses SQL Actual data, can contain multiple tables Bound controls display data

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Connection Used to establish link form specific file or database to program Types –SqlConnection Microsoft SQL Server databases only –OleDBConnection All other databases

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Setting Up a Connection Can be accomplished from –Toolbox –Server Explorer window –Within Data Adapter Configuration Wizard using New Connection button No matter which method above is used to begin the connection, the Data Link Properties dialog appears for you to complete the task

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Creating a Connection from Server Explorer Click Connect to Database button OR Right-click Data Connections

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Data Link Properties Dialog Used to define Connection's –OLE DB Provider –Actual DB Filename –Logon UserName and Password (optional) Used to Test Connection

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Connections in Server Explorer Shows all created Connections Same Connection can be use for multiple projects Expand Connection node to view tables and fields

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Data Adapter Does all the work of passing data back and for the between a data source and a program Does not have to be a database Can be text file, object, or even an array Types, must match Connection type –OleDbDataAdapter –SqlDataAdapter Use db prefix (e.g. dbRnR)

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Setting Up a Data Adapter from Server Explorer Drag Table name to form OR CTRL-click Field names and drag to form

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Data Adapter Configuration Wizard Walks you through the steps for selecting fields in a database Only used if you create/add a Data Adapter from the Toolbox Can be used to modify existing Data Adapters also

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Dataset Temporary set of data stored in memory In ADO.NET datasets are disconnected; the copy of data kept in memory does not keep an active connection to the data source Dataset may contain multiple tables and relationships

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Defining a Dataset Drag Dataset control from the toolbox to form Select Data menu, Generate Dataset Right-click on Data Adapter and select Generate Dataset In all cases, you see the Generate Dataset dialog box

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Defining a Dataset (cont.) Name dataset with ds prefix in Generate Dataset dialog (e.g. dsBooks)

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Data Passing from Data Source to Dataset to User Interface Data Object (Class) Windows Forms Web Forms Data Adapter Presentation TierBusiness TierData Tier Dataset Data Source XML

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved XML Data Industry-standard format for storing and transferring data Specifications at World Wide Web Consortium (W3C) The needed XML for accessing databases will be automatically generated for you in Visual Basic

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved XML Data stored in XML is all text XML Data File –Contains actual data XML Schema File –Contains descriptions for Fields Data Types Constraints, such as required fields –.xsd file in Solution Explorer

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Fill Method Method of the Data Adapter executed at run time to fill the dataset Usually coded in Form_Load (or Page_Load for Web Projects) General Form DataAdapterName.Fill (DataSetName) Example dbRnR. Fill (dsBooks1)

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Creating Bound Controls: Data Grid In Windows Form –Set properties of the controls –Use Fill method Example: Grid Control –New control in VB.NET –Displays database records as a table Steps –Set up/add Connection, DataAdapter, DataSet –Add DataGrid control from toolbox (dbg prefix)

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Creating Bound DataGrid Steps continued –Set properties of DataGrid to bind to data DataSource to DataSet name DataMember to Table name –Add code to populate control with data Windows Form, Form_Load ==> DataAdapterName.Fill (DataSetName )

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Creating Simple Bound Controls Labels and text boxes Same steps: –Set up/add Connection, DataAdapter, DataSet –Add text boxes or label control from toolbox –Set properties to bind to data Data Binding properties menu Text option to be specified –Add code to populate control with data Windows Form, Form_Load ==> DataAdapterName.Fill (DataSetName )

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Navigating Through DataSets Refer to the Position and Count properties of the Windows Form's BindingContext ' Move to next record Me.BindingContext(dsBooks1, "Books").Position + = 1 ' Move to previous record Me.BindingContext(dsBooks1, "Books").Position - = 1 ' Move to the first record Me.BindingContext(dsBooks1, "Books").Position = 0 ' Move to the last record With Me.BindingContext(DsCustomer1, "Customer").Position =.Count - 1 End With

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Retrieving Record Count Specify –DataSet –Table Name –Rows Collection –Count Property Example intRecordCount=dsBooks1.Tables("Books").Rows.Count ‘Ulternatively Me.BindingContext(DsCustomer1, "Customer").Count

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Updating a Database File Types of updating –Modify existing records –Add records –Delete records Must display the dataset in bound controls that can be used for input (no labels) You must write code to actually update the database

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Typical Form for Updating Save Button is enabled only when an Add or Edit is in progress Add caption changes to Cancel during Add or Edit All Navigation Buttons are disabled during Add or Edit

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Update Method Method of DataAdapter used to write changes to database ‘General Form DataAdapterName.Update (DataSet, "Table") ‘Example dbRnR. Update (dsBooks1, "Books") Can be executed –After every change, perform data validation, then execute Update (Save Record button) –Once, just before program termination for all changes execute Update (Form's Closing event)

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Update Method (cont.) Automatically loops through the records in a table to determine what type of update is needed and then performs the required SQL –Update –Insert –Delete Execute during Form's Closing event if running once to apply all changes

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Example - Update Form's Closing Event ' mblnIsDirty was declared in Declarations section 'Save changes, Update Database If mblnIsDirty Then If MessageBox.Show("Save Changes?", "Books" _ MessageBoxButtons.YesNo, _ MessageBoxIcon.Question ) = DialogResult.Yes Then Try dbRnR.Update(dsBooks1, "Books") Catch MessageBox.Show("Error saving file", "Books") End If

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Logic of Update Programs Enclose all statements that access the database in Try/Catch blocks Display data in bound input controls –Initially set ReadOnly property = True When user clicks Edit button –Set ReadOnly = False –Disable Navigation buttons –Provide Cancel and Save buttons for user

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Saving Changes Logic - User Clicks Save Button Perform Data Validation –If valid data then Set ReadOnly = True Set mblnDirty = True Enable Navigation buttons Disable Save button –If invalid data then Notify user with MessageBox Set focus to control containing invalid data

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Canceling Changes Logic - User Click Cancel Button Replace changed values in controls with original values –See RejectChanges procedure (p 441) –Set ReadOnly = True –Enable Navigation buttons –Disable Save button

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Deleting Records Execute Delete Method of the table's Rows collection Example Dim intCurrRecNum As Integer intCurrRecNum = Me.BindingContext(dsBooks1, _ "Books").Position dsBooks1.Books.Rows(intCurrRecNum).Delete ( ) mblnIsDirty = True

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Adding Records If user clicks Add button –Clear bound input controls –Set ReadOnly = False –Set mblnAdding = True –Disable Navigation buttons –Provide Cancel and Save buttons for user Logic for Save and Cancel are same as on previous slide except for resetting mblnAdding to False

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Example - Saving an Added Record Dim newRow As DataRow = dsBooks1.Books.NewRow newRow("Author") = txtAuthor.Text newRow("ISBN") = txtISBN.Text newRow("Title") = txtTitle.Text dsBooks1.Books.Row.Add(newRow)

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Logic for Save Button Must determine type of operation in progress since used for saving changes made as –Edits –Adds Use mblnAdding variable to identify Add operations in progress

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Bound Combo Boxes Provides an easy user interface for selecting records to view or update Windows Forms –Use ListBox or ComboBox Web Forms –Use ListBox or DropDownList

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Using Multiple Data Adapters Use when more than 1 dataset or more than 1 table in a dataset is needed A single Connection object can supply the connection for more than 1 data adapter Useful when a list is available for the user to select the record(s) to display –1 dataset for the list itself –1 dataset for the selected record(s)

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Parameterized Query DataSet with special type of SQL SELECT statement –WHERE clause is incomplete until user enters value for criteria at run time –Uses question mark in place of criteria Example SELECT Title, Author, ISBN FROM books WHERE Title = ?

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Filling a List - Windows Forms Set ListBox or ComboBox Properties –DataSource to DataSet name –DisplayMember to table name.field name Use Fill method to populate list with data Tip: To eliminate duplicate entries in the list. Modify the SQL SELECT statement to include the DISTINCT keyword.

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Displaying the Data for the Selected Item At run time the user may enter the value to be used in the Parameterized Query in –TextBox Include an associated button for the user to click to use the value Be sure to check for possible empty dataset if the user enters a value not in the dataset –Selection of a ListBox or ComboBox Write code in the SelectedIndexChanged Event

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Example ' Get record to match selected title in list dsBooks1.Clear( ) dbRnR.SelectCommand.Parameters("Title").Value =cboTitles.Text dbRnR.Fill(dsBooks1) Combo box SelectedInexChange Event TextBox, Associated Button's Click Event ' Get record to match selected title in list dsBooks1.Clear( ) dbRnR.SelectCommand.Parameters("Title").Value = txtTitles.Text dbRnR.Fill(dsBooks1) If dsBooks1.Tables("Books").Rows.Count = 0 Then MessageBox.Show("Title not found.")

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Making Database Projects Portable Connection information is directly tied to database file location You must move database AND –Create Connection on new computer –Configure DataAdapter –For Web Projects, also create Virtual Directory Less problems if you store the database in the same folder as your project

© 2001 by The McGraw-Hill Companies, Inc. All rights reserved Command Summary ' Data Adapter fills a Dataset. dbRnR. Fill (dsBooks1) ' Move to next, pervious, first and last record Me.BindingContext(dsBooks1, "Books").Position [+ = 1, -=1, 0,.Count –1] ‘Retrieving record count intRecordCount=dsBooks1.Tables("Books").Rows.Count ' Get record to match selected title in list dbRnR.SelectCommand.Parameters("Title").Value =cboTitles.Text ' Save the changes in the file dbRnR. Update (dsBooks1, "Books") ‘Add a new record Dim newRow as DataRow = DsCustomer1.Customer.NewRow dsBooks1.Books.Row.Add(newRow) ' Delete current record dsBooks1.Books.Rows(intCurrRecNum).Delete ( )