Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "ADO.NET in VB.NET 2005 ITE 370 4/26/2017."— Presentation transcript:

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

2 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

3 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

4 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

5 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

6 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,

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

8 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

9 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

10 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

11 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

12 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

13 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

14 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

15 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

16 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

17 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

18 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

19 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

20 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

21 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

22 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

23 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

24 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

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

26 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

27 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

28 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

29 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

30 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

31 Sample Code 4/26/2017

32 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

33 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

34 Sample Code 4/26/2017

35 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

36 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

37 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

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

39 Sample Code 4/26/2017

40 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

41 Binding the DataGridView
4/26/2017

42 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

43 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

44 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


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

Similar presentations


Ads by Google