ADO.NET in VB.NET 2005 ITE 370 4/26/2017.

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.
BIM211 – Visual Programming Database Operations 1.
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.
1 Web-Enabled Decision Support Systems Advance Topics in Database Connectivity Prof. Name Position (123) University Name.
Chapter 10 ADO. What is ADO? ADO is a Microsoft technology ADO stands for ActiveX Data Objects ADO is a programming interface to access data in a database.
Chapter 12: Using ADO.NET 2.0 Programming with Microsoft Visual Basic 2005, Third Edition.
Guide to Oracle10G1 Introduction To Forms Builder Chapter 5.
Introduction to Database Processing with ADO.NET.
VB.NET Database Access ISYS546. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
Using ADO.NET Chapter Microsoft Visual Basic.NET: Reloaded 1.
A Guide to Oracle9i1 Introduction To Forms Builder Chapter 5.
1 ADO.NET. 2.NET Framework Data Namespaces System.Data –Base set of classes and interfaces for ADO.NET System.Data.Common –Classes shared by the.NET Data.
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.
Introduction to ADO.Net and Visual Studio Database Tools ISYS 512.
VB.NET Database Access ISYS546. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS 512.
C# Programming: From Problem Analysis to Program Design1 Working with Databases C# Programming: From Problem Analysis to Program Design 3 rd Edition 14.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS 512.
From VS C# 2010 Programming, John Allwork 1 VS2010 C# Programming - DB intro 1 Topics – Database Relational - linked tables SQL ADO.NET objects Referencing.
Chapter 8 Binding Data to Web Controls. ASP.NET 2.0, Third Edition2.
CHAPTER 9 DATABASE MANAGEMENT © Prepared By: Razif Razali.
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.
Introduction to ADO.Net and Visual Studio Database Tools ISYS 512.
10-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
ADO.NET A2 Teacher Up skilling LECTURE 3. What’s to come today? ADO.NET What is ADO.NET? ADO.NET Objects SqlConnection SqlCommand SqlDataReader DataSet.
CIS 451: Using ASP.NET Objects with SQL Dr. Ralph D. Westfall February, 2009.
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.
Databases and Data Access  Introduction to ADO.NET  ADO.NET objects  ADP.NET namespaces  Differences between ADO and ADO.NET.
.NET Data Access and Manipulation ADO.NET. Overview What is ADO.NET? Disconnected vs. connected data access models ADO.NET Architecture ADO.NET Core Objects.
Objectives In this lesson, you will learn to: *Identify the need for ADO.NET *Identify the features of ADO.NET *Identify the components of the ADO.NET.
ASP.NET Rina Zviel-Girshin Lecture 5
Session 8: ADO.NET. Overview Overview of ADO.NET What is ADO.NET? Using Namespaces The ADO.NET Object Model What is a DataSet? Accessing Data with ADO.NET.
Module 7: Accessing Data by Using ADO.NET
Using Adapter Wizard ISYS 512. Data Adapter Wizard – 2 nd Level of Using ADO.Net Configure Data Adapter and generating a dataset: –From the Data tab of.
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)
Chapter Thirteen Working with Access Databases and LINQ Programming with Microsoft Visual Basic th Edition.
1 Data Classes- DataView DataGridView Control. Objectives 2  Data Class  DataAdapter  DataReader  DataSet  DataTable  DataView  DataGridView Control.
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.
Mauricio Featherman, Ph.D. Washington St. University
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.
HNDIT Rapid Application Development
1 Database Programming with ADO.NET Kashef Mughal.
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.
Chapter 9 Working with Databases. Copyright © 2011 Pearson Addison-Wesley Introduction In this chapter you will learn: – Basic database concepts – How.
Data Access. ADO.NET ADO.NET is the primary library for building database solutions within the.NET Framework. ADO.NET does not replace ADO. ADO and OLEDB.
ADO .NET from. ADO .NET from “ADO .Net” Evolution/History of ADO.NET MICROSOFT .NET “ADO .Net” Evolution/History of ADO.NET History: Most applications.
Programming with Microsoft Visual Basic 2012 Chapter 14: Access Databases and SQL.
.NET Data Access and Manipulation
Programming with Microsoft Visual Basic 2012 Chapter 13: Working with Access Databases and LINQ.
Common SQL keywords. Building and using CASE Tools Data Base with Microsoft SQL-Server and C#
Microsoft Visual Basic 2010: Reloaded Fourth Edition
Introduction to Database Processing with ADO.NET
ADO.NET Framework.
Lecture 6 VB.Net SQL Server.
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:

ADO.NET in VB.NET 2005 ITE 370 4/26/2017

What is ADO.NET? An acronym for the .NET version of ActiveX Data Objects A .NET Framework Class Library A group of types that reside in System.Data namespace A technology used by client applications to work with stored data Supported data formats include: relational databases (MS-Access, SQL-Server, and Oracle) Spreadsheets and other file formats XML ADO.Net are the Active X Data Objects in Visual Studio – They connect application program to data sources (Relational Databases, Excel Spreadsheets, etc.) Resides in System.Data namespace (library) – We will need to Import System.Data.* in applications 4/26/2017

Providers and Their Namespaces What is a “provider”? .NET data provider Software for accessing a specific source of data, such as SQL-Server Optimized classes for SQL-Server Namespace: System.Data.SqlClient OLE DB client For MS-Access, Excel, and others Also has support for Oracle and SQL-Server Namespace: System.Data.Oledb Normally, since it has support of Access and Sql-Server we will import System.Data.Oledb 4/26/2017

How clients, .NET data providers &DBMSs fit together SQL .NET Data Provider OLE DB other .NET data providers MS Access Server Client – Our windows application. This can reside at a different physical location We need to use the correct data provider to connect to the database other DBMS 4/26/2017

Types of ADO.NET objects Connection – establishes links to data sources Command – stores and executes commands (i.e. queries and stored procedures with parameters) DataReader – provides sequential, read-only access to data TableAdapter – pulls data from one or more database tables and passes it to your program DataSet – an in-memory copy of data pulled from the database tables (by the Table Adapter) DataTable – stores a relation—eg. the result of a query DataRelation – defines a relationship between two DataTables DataRow – stores a single row/record of a data table DataColumn – represents schema in a column of a DataTable DataView -- customized view of a DataTable for sorting, filtering, searching, editing, and navigation. DataGrid – tabular control for displaying/editing a data source We need to know what we want to do when we connect to the data source so we know what data objects we will need to create. Search  Read Edit  Modify CRUD  Create / Read / Update / Delete First focus on Connection, Command and Data Reader Connection – Connect the application to the data Supply the name and location of the Database Provider – the data source Provide username and password Verify connection (This can be a maintained connection or a Just In Time Connection that is opened and closed as needed) The Data Source is stored as a property of the Connection object Command – Allows us the CRUD capabilities with the data source Store Queries (Select, Insert, Update, Delete) Use Stored Procedures with Parameters (Reside at the Database Tier) Data Reader – Holds the data in the application program to allow use to work with the data 4/26/2017

Working with .udl files to build connection strings To create a UDL file: 1.      Open Windows Explorer or My Computer. 2.      Select the folder in which you want to save the .UDL file. 3.      On the File menu, click NEW and then click Text Document. 4.      Right-click on the text file you created in step 3, then click Rename. Type the new file name using a .udl file extension. Press Enter. For example. Myudl.UDL 5.      You may get a warning, message box, explaining that changing file extensions may cause files to become unusable. This is fine, click OK.   Once you have created the UDL file, you must now configure it: Double click on the UDL file to bring up the Data Link Properties Dialog Box. Click on the Providers tab and select the driver you wish to use. Click on the Connection tab and enter the connection properties, each driver will require different settings, so I will not go into much details. All drivers will require a user name and password. Click on the “Test Connection” button to verify your connection is working correctly. Change accordingly if you get an error. Select the advanced tab only if you require advanced settings. The Data Like Wizard will build a data source property string that we will then paste into our programs (Very complicated string, you can create yourself if you want to) Access 2003 requires the Microsoft Jet 4.0 OleDB provider An error on the connection could be a wrong version of the provider. We can then open this file in Notepad to see (and later copy) the connection string. 4/26/2017 Source: K & K Consulting, http://kandkconsulting.tripod.com/VB/Tutorials/udl_file_tutorial.htm

Create Data Source String for Connection Object Example of how to create the Data Source String 4/26/2017

DataReader Class The DataReader Provides forward-only, read-only access to data Analogous to reading a sequential file Read from beginning of file in order to the end of file Fast access to data Uses little memory Requires connection and command objects to use 4/26/2017

DataReader Example Imports System.Data.Oledb Public Class ConnDb '* Declare constant to hold base connection string information '* for connecting to an MS-Access baseball database (connection string from UDL file). Public Const ConnStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;" _ & "Persist Security Info=False;Data Source=“ ‘* notice we removed name of file End Class '* Declare data access objects Dim conTeamDb As OleDbConnection '* connects to baseball database Dim dbCommand As OleDbCommand '* executes database query for team Public rdrTeams As OleDbDataReader '* forward-only, read-only access to team relation Dim OpenDbDialog As New OpenFileDialog ‘* If the user selects a database in the open dialog box... If OpenDbDialog.ShowDialog() = DialogResult.OK Then '* connect to the database conTeamDb = New OleDbConnection(ConnDb.ConnStr & OpenDbDialog.FileName) conTeamDb.Open() '* query the team table, assigning result to a data reader dbCommand = New OleDbCommand("SELECT Location, Nickname, Stadium, League FROM Team", conTeamDb) rdrTeams = dbCommand.ExecuteReader If rdrTeams.Read() '* success reading next team Console.WriteLine(rdrTeams.Item("Location") & " " & rdrTeams("Nickname")) End if rdrTeams.Close() conTeamDb.Close() End If Code Example of Data Reader Storing the connection string as a constant (in fact it is stored as a class) allows us to use it throughout the application as necessary 4/26/2017

View Sample Project Using Data Reader Create New VB.Net Application Add ListTeams.VB Project Properties  StartUP Sub Main ( ) Run Sample Application Using Data Reader Attempt to Add a Form and Have the Data Display within the Form instead of to the Console Incorrect Queries will result in a Run Time Error (Create and test in the Database, then copy into the application) Look in MSDN or Textbooks to find out more about the Connection, Command, and DataReader Objects. 4/26/2017

Using Table Adapters / Data Set Table Adapter – Retrieves data from the data source and updates the data in the data source Data Connection – Connecting to the Data Source Built into the Table Adapter Object Data Set – In memory copy of records / data tables Separate from the data source Data tables have columns and rows Allows you to work with the data from the data source Changes are not permanent in external data source unless directed by the Table Adapter Data is transferred from the data source to the data set and vice-versa through the Table Adapter 4/26/2017

DataSet w/Multiple Tables & Providers 1) Fill(DataSet, “TableX”) SQL Server 3) Return DataTable SqlTableAdapter DataSet SelectCommand 2) Execute query TableX TableY Oracle OleDbTableAdapter This slide shows multiple data sets with multiple data providers. 2 Types of Table Adapters: SQL  Sql-Server OleDB  Generic, including Access and Oracle The data reader was forward only / read only access The Data Set gives us FULL Power – forward / backwards, read / write capabilities Object Oriented representation of the data source / database Data Set – one or more data tables A data table is like a data reader only with read / write access It can be an actual table or the result of a query A data set encapsulates the data tables into one named set The Table Adapter’s Fill Method will fill (or create) the data table The Table Adapter’s Command Object contains the Select Command Connection to DB Command to invoke query to build table (retrieve data from database and build the data table) The DataSet / DataTable method uses more memory and is slightly slower than the data reader You can create multiple data tables with the Table Adapter – Even from different data sources 6) Return DataTable SelectCommand 5) Execute query 4) Fill(DataSet, “TableY”) 4/26/2017

TableAdapter Class Provides communication between the application and database Represents a set of data commands and a database connection that are used to fill the DataSet and update the data source based on queries Can contain multiple queries – called like methods Created with Code Dataset Designer During Creation of a New Dataset – Data Source Configuration Wizard Server Explorer / Dataset Designer To Declare a TAble Adapter Dim in Code OR Available in Design Window when creating, datasets Command Properties: Select Insert Update Delete These maybe too powerful, they build commands for you to interact with the database Fill: Select command to retrieve data from the Database Update: Saves the changes made to the Data Table and saves to the original data source (database) 4/26/2017

TableAdapter Class __Command properties (Created through Queries): Select Query – Used in Fill Method Insert Command, Update Command, Delete Command Can be Created by default if enough information is available in the Select query (Fill Method) Methods: Fill – populated the Data Table with the result of the select command Update – Sends changes back to the database Insert – creates a new row in the data table ClearBeforeFill – Clears the data table before executing a fill method 4/26/2017

TableAdapter: __Command Properties Contain command objects to perform operations against the underlying database Select Command Populates a DataTable with the results of a query Uses SQL SELECT statement typically Insert Command Inserts rows added to a DataTable into database Uses SQL INSERT statement 4/26/2017

TableAdapter: __Command Properties (cont.) Update Writes changes made to a DataTable into the underlying database Uses SQL UPDATE statement Delete Command Makes deletions of rows in a DataTable permanent by deleting those rows from the database Uses SQL DELETE statement 4/26/2017

DataAdapter: Fill Method Adds or refreshes rows in the DataSet to match those in the data source using the DataSet name Creates a DataTable named "Table" taEmployee.Fill(dsCompany.AllEmployees) The fill method gives the DataTable a name If a data table already exists with this name it will APPEND to it Name for Data Table Table Adapter Method Data Set 4/26/2017

TableAdapter: Update Method Used to persist changes to a DataTable (i.e. save them in the database) Calls the respective INSERT, UPDATE, or DELETE statements for each inserted, updated, or deleted row in the specified DataSet from a DataTable named "Table" taEmployee.UpdateCommand(dsEmployee) Stores the changes made in the data table in the original data source / database 4/26/2017

Table Adapter – Through IDE Server Explorer Click on Connect to DB Icon Add Connection Provide Data Source Type (Access, SQL Server) Provide Database File Test the Connection Add DataSet Data Menu  Add New Data Source Project  Add New Item  DataSet Select Items from Open Connection in Server Explorer Creates the Data Set and Table Adapter 4/26/2017

Binding Source Data Aware Controls Controls that can automatically display data from a table cell in the DataSet (most VB.net controls are data aware) Controls must be Bound to the DataSet DataBindings Property of Control Arrow next to Text Field (of DataBindings) Add or Select Data Source Complete Data Source Configuration Wizard 4/26/2017

Currency Manager Object that gives a way of navigating the rows of the DataTable. One row of the DataTable is always the current row Data Aware controls display the data from the current row Currency Manager objects are included in BindingSource components Position Property  Number of the Current Row (zero based) Count Property  How many rows are in the table 4/26/2017

Sample Code Create a Visual Basic 2005 Application that will access the Baseball3 database and display the player information in bound textboxes. The program should use a Table Adapter, Data Set , Binding Source and Currency Manager to manipulate through the table data. 4/26/2017

Visual Studio.Net Wisdom Update Command TableAdapter.Update (Dataset.DataTable) taEmployee.Fill(dsCompany.AllEmployees) Updates the database Updates the “local” copy in the Bin directory Copied over by Visual Studio the next time the program is run Don’t want you to corrupt your databases How to accomplish a True Update????? 4/26/2017

Update Command Cannot use the IDE to develop your application Must create the code by hand (Within Class Code) Connection Object DataAdapter Object DataSet Object DataTable Object BindingSource Object CommandBuilder Object Import System.Data.OleDb (will be System.Data.SQL for SqlServer) 4/26/2017

Connection Object Create the connection to the data source Uses the Connection String Information Dim myConnection as New OleDb.Connection (connectionString) 4/26/2017

Data Adapter Object Table Adapter is Not an Option Here, we must use a Data Adapter Dim myDataAdapter as New OleDbDataAdapter (“sqlCommand”, connectionObject) 4/26/2017

Data Set Object Create the Data Set Dim myDataSet as New DataSet (“DataSetName”) Name of DataSet is a String, it must be in Quotation Marks 4/26/2017

Data Table Object Create the Data Table Will Store the Data for the Data Set in Table form Dim myDataTable as New DataTable (“DataTableName”) Data Table Name is a string, it must be in Quotation Marks 4/26/2017

Binding Source You must create a Binding Source Object to bind your data controls to the DataSet Dim myBindingSource as New BindingSource 4/26/2017

Command Builder Fill Command is automatically created for the Data Adapter Object In an OleDb Connection a Command Builder object is needed to create the additional commands including Update Dim myBuilder as New OldDbCommandBuilder (NameOfDataAdapterObject) 4/26/2017

Sample Code 4/26/2017

Form Load Event Open the Connection Add the DataTable to the DataSet connectionObject.Open( ) Add the DataTable to the DataSet dataSetObject.Tables.Add(dataTableObject) Fill the DataSet through the DataAdapter dataAdapterObject.Fill(dataSetObject, “StringName of DataTable”) Bind the DataTable to the BindingSource bindingSourceObject.DataSource = dataTableObject 4/26/2017

Form Load Events (Con’t) Bind the Controls to the DataTable Allows Bound Controls to Display Data from DataTable controlName.DataBindings.Add (“text”, bindingSourceObject, “FieldName”) “text” must be typed exactly as seen “FieldName” is the name of the column from the Data Table – typically the name of the field in the Database (unless an alias is created by the SQL command) 4/26/2017

Sample Code 4/26/2017

BindingSource Object BindingSource Object can manipulate through the DataTable CurrencyManager is NOT Needed BindingSource.Position BindingSource.Count BindingSource.MoveNext( ) BindingSource.MovePrevious( ) BindingSource.MoveFirst( ) BindingSource.MoveLast( ) 4/26/2017

Finalizing Update EndEdit on the BindingSource Update the DataAdapter Stops the Editing through the Binding Source bindingSourceObject.EndEdit ( ) Update the DataAdapter Send Changes back to Original Data Source dataAdapterObject.Update (dataSetObject, “stringNameOfDataTable”) Close the Connection connectionObject.Close ( ) 4/26/2017

DataGridView class The Windows Forms DataGridView control Provides a user interface to ADO.NET datasets displays tabular data allows for updates to the data source Data Grid gives a Tabular Representation of data in a database – DTG prefix Value of a Data Grid – Users can view multiple rows and columns of data at one time, in a table (grid) format - Column headings are assigned from the data source, can be overridden - Scroll bars as necessary (best to show as much as possible in the window, especially important to show all columns) - Show information that is IMPORTANT and MEANINGFUL to the user (you may need to store some data but not show it) - User can modify data in the data grid and then update the database (update method from data adapter) Be VERY careful with this – the USER control the actions, Verify Updates and Deletes 4/26/2017

Creating DataGridView Program Connection Object DataAdapter Object DataSet Object DataTable Object CommandBuilder Object No BindingSource object needed – Property of DataGridView 4/26/2017

Sample Code 4/26/2017

Binding the DataGrid The DataGrid can receive data from any of the following data sources: DataTable class DataView class DataSet class DataViewManager class dtgObject.DataSource=dataTable dtgPlayer.DataSource = myPlayerTable Working with the data grid Connecting the the data source: DataTable DataView DataSet (contains one or more data tables) DataViewManager 4/26/2017

Binding the DataGridView 4/26/2017

Current row and cell Users can navigate on the DataGridViewer CurrentRow.Index Holds zero-based integer for highlighted row CurrentCell property Gets or sets which cell has the focus Contains DataGridViewCell object Has ColumnNumber and RowNumber properties Item property holds cell content ‘* display cell contents of third column Console.WriteLine(dtgTeam.Item(dtgTeam.CurrentRowIndex, 2)) To Access the Current Cell / Row (the one selected by the user) Zero Based Integer CurrentRowIndex CurrentCell (has the focus) ColumnNumber RowNumber Item Collection – holds the cell content 4/26/2017

Data in DataGridViewer Read Only dtgObject.ReadOnly = True Storing a column in the DataGridView that you don’t want users to see (eg. Primary key field) dtgObject.Columns(index).Visible = False 4/26/2017

Data Grid Example - Homework Use Baseball Database (Baseball3.mdb) DataGridView Example Create Form with DataGridView Object Create Needed Objects (in Code) Hidden Column (Primary Key) TeamID Column – Read Only Update Database on Exit Button Bonus: User OpenFileDialog box to Select Database 4/26/2017