Presentation is loading. Please wait.

Presentation is loading. Please wait.

Developing Web Applications Using Microsoft ® Visual Studio ® 2008.

Similar presentations


Presentation on theme: "Developing Web Applications Using Microsoft ® Visual Studio ® 2008."— Presentation transcript:

1 Developing Web Applications Using Microsoft ® Visual Studio ® 2008

2 Module 5: Accessing Data with Microsoft ADO.NET and Visual Studio 2008 Overview of ADO.NET Connecting to a Database Accessing Data Accessing Multiple Tables

3 Lesson: Overview of ADO.NET What Is ADO.NET? The ADO.NET Object Model DataSets and DataReaders Accessing Data with ADO.NET

4 What Is ADO.NET? ADO.NET provides a set of classes for working with data. ADO.NET is: An evolutionary, more flexible successor to ADO A system designed for disconnected environments A programming model with advanced XML support A set of classes, interfaces, structures, and enumerations that manage data access in the.NET Framework

5 The ADO.NET Object Model DataSet DataTable ODBC Data Provider ODBC Data Provider SQL Server Data Provider SQL Server Data Provider OLE DB.NET Data Provider OLE DB.NET Data Provider Oracle Data Provider Oracle Data Provider ODBC sources SQL Server 7.0 (and later) OLEDB sources (SQL Server 6.5) Oracle sources

6 DataSets and DataReaders DataSetDataReader Read/write access to dataRead-only Includes multiple tables from different databases Based on one SQL statement from one database DisconnectedConnected Bind to multiple controlsBind to one control only Forward and backward scanning of data Forward-only Slower accessFaster access Supported by Visual Studio 2008 Designer Manually coded

7 Database Client makes request Create a SqlDataSource Client manipulates the data Update the data Use the SqlDataSource to open a database connection, update the database, and close the connection Accessing Data with ADO.NET GridView Control Client Web server SqlDataSource Return the data to the client 1 1 2 2 3 3 4 4 5 5 6 6

8 Lesson: Connecting to a Database Generating a Connection by Using Server Explorer The DataAdapter Object Model Generating a DataSet Creating a Connection Programmatically

9 In Server Explorer, right-click Data Connections, and then click Add Connection. Configure the connection Generating a Connection by Using Server Explorer

10 Command The DataAdapter Object Model SELECT SelectCommandUpdateCommandInsertCommandDeleteCommand DataAdapter UPDATEINSERTDELETE Database DataSet Connection

11 Generating a DataSet Creating a DataSet Filling the DataSet [Visual Basic] Dim myDataSet As _ New DataSet() [Visual Basic] Dim myDataSet As _ New DataSet() [Visual C#] DataSet myDataSet = new DataSet(); [Visual C#] DataSet myDataSet = new DataSet(); [Visual Basic] myDataAdapter1.Fill(ds) myDataAdapter2.Fill(ds) [Visual Basic] myDataAdapter1.Fill(ds) myDataAdapter2.Fill(ds) [Visual C#] myDataAdapter1.Fill(ds); myDataAdapter2.Fill(ds); [Visual C#] myDataAdapter1.Fill(ds); myDataAdapter2.Fill(ds);

12 Creating a Connection Programmatically Creating a SqlConnection instance Setting connection string parameters  Connection timeout  Data source  Initial catalog  Integrated security  Password  Persist security info  Provider  User ID [Visual Basic] Dim connectionString As String = "data source=localhost; " & _ "initial catalog=northwind; integrated security=true" Dim connection As New SqlConnection(connectionString) [Visual Basic] Dim connectionString As String = "data source=localhost; " & _ "initial catalog=northwind; integrated security=true" Dim connection As New SqlConnection(connectionString) [Visual C#] string connectionString = "data source=localhost; " + "initial catalog=northwind; integrated security=true"; SqlConnection connection = new SqlConnection(connectionString); [Visual C#] string connectionString = "data source=localhost; " + "initial catalog=northwind; integrated security=true"; SqlConnection connection = new SqlConnection(connectionString);

13 Lesson: Accessing Data Binding Data to Controls by Using the IDE Creating a Command Object Creating a DataReader Retrieving Data by Using a DataReader Creating a DataSet Displaying a DataSet in a List-Bound Control Handling Errors

14 Add a GridView control to the Web Form Bind the GridView control to a SqlDataSource control that contains the connection and query information SqlDataSource properties:  ConnectionString. The connection string to connect to the database.  ProviderName. The database type. GridView properties:  Columns. The set of columns to be shown in the control  DataSourceID. The control ID of a data source Binding Data to Controls by Using the IDE

15 Creating a Command Object ExecuteReader. Returns a DataReader object ExecuteScalar. Returns a single scalar value object ExecuteNonQuery. Executes a command that does not return any rows ExecuteXmlReader. Returns an XmlReader object [Visual C#] myCommand.Connection.Open(); SqlDataReader myDataReader = myCommand.ExecuteReader(); // Process the results. myCommand.Connection.Close(); [Visual C#] myCommand.Connection.Open(); SqlDataReader myDataReader = myCommand.ExecuteReader(); // Process the results. myCommand.Connection.Close(); [Visual Basic] myCommand.Connection.Open() Dim myDataReader As SqlDataReader = myCommand.ExecuteReader() ' Process the results. myCommand.Connection.Close() [Visual Basic] myCommand.Connection.Open() Dim myDataReader As SqlDataReader = myCommand.ExecuteReader() ' Process the results. myCommand.Connection.Close()

16 Creating a DataReader Create and open the database connection Create a Command object Create a DataReader from the Command object Call the ExecuteReader method Use the DataReader object 1 1 2 2 3 3 4 4 5 5 Close the DataReader object Close the Connection object 6 6 7 7

17 Retrieving Data by Using a DataReader Call Read for each record  Returns false when there are no more records Access fields  Parameter is the ordinal position or name of the field  Get functions give best performance Close the DataReader Close the connection [Visual Basic] Do While myDataReader.Read() text &= myDataReader(1) text &= myDataReader ("field") text &= myDataReader.GetDateTime(2) Loop [Visual Basic] Do While myDataReader.Read() text &= myDataReader(1) text &= myDataReader ("field") text &= myDataReader.GetDateTime(2) Loop [Visual C#] while (myDataReader.Read()) { text += myDataReader[1]; text += myDataReader["field"]; text += myDataReader.GetDateTime(2); } [Visual C#] while (myDataReader.Read()) { text += myDataReader[1]; text += myDataReader["field"]; text += myDataReader.GetDateTime(2); }

18 Creating a DataSet Create and populate a DataSet with DataTable objects  Fill method executes the SelectCommand Access a DataTable [Visual Basic] Dim myDS As New DataSet() myDA.Fill(myDataSet, _ "Authors") [Visual Basic] Dim myDS As New DataSet() myDA.Fill(myDataSet, _ "Authors") [Visual C#] DataSet myDS = new DataSet(); myDA.Fill(myDataSet, "Authors"); [Visual C#] DataSet myDS = new DataSet(); myDA.Fill(myDataSet, "Authors"); [Visual Basic] myDS.Tables( _ "Authors").Rows.Count... Dim row As DataRow Dim text As String For Each row in myDS.Tables("Authors").Rows text &= r(1) text &= r("LastName") Next [Visual Basic] myDS.Tables( _ "Authors").Rows.Count... Dim row As DataRow Dim text As String For Each row in myDS.Tables("Authors").Rows text &= r(1) text &= r("LastName") Next [Visual C#] myDataSet.Tables[ "Authors"].Rows.Count;... string text = ""; foreach(DataRow row in myDS.Tables["Authors"].Rows) { text += row[1]; text += row["LastName"]; } [Visual C#] myDataSet.Tables[ "Authors"].Rows.Count;... string text = ""; foreach(DataRow row in myDS.Tables["Authors"].Rows) { text += row[1]; text += row["LastName"]; }

19 Displaying DataSet Data in List-Bound Controls Set the properties Fill the DataSet, then call the DataBind method [Visual Basic] myDataAdapter.Fill(myDataSet) employeesList.DataBind() [Visual Basic] myDataAdapter.Fill(myDataSet) employeesList.DataBind() [Visual C#] myDataAdapter.Fill(myDataSet) employeesList.DataBind(); [Visual C#] myDataAdapter.Fill(myDataSet) employeesList.DataBind(); PropertyDescription DataSourceThe DataSet containing the data DataMemberThe DataTable in the DataSet DataTextFieldThe field in the DataTable that is displayed DataValueField The field in the DataTable that becomes the value of the selected item in the list

20 [Visual Basic] Catch ex1 As System.Data.SqlClient.SqlException Select Case ex1.Number... Case 18452 errorsLabel.Text = errorsLabel.Text & _ ("Invalid user name")... End Select End Try [Visual Basic] Catch ex1 As System.Data.SqlClient.SqlException Select Case ex1.Number... Case 18452 errorsLabel.Text = errorsLabel.Text & _ ("Invalid user name")... End Select End Try Handling Exceptions Connection will not open  Connection string is invalid  Server or database not found  Login failed [Visual C#] catch (System.Data.SqlClient.SqlException ex1) { switch(ex1.Number) {... case 18452: errorsLabel.Text = errorsLabel.Text + ("Invalid user name"); break;... } [Visual C#] catch (System.Data.SqlClient.SqlException ex1) { switch(ex1.Number) {... case 18452: errorsLabel.Text = errorsLabel.Text + ("Invalid user name"); break;... } DataAdapter cannot create a DataSet  Invalid SQL syntax  Invalid table or field name

21 Lesson: Accessing Multiple Tables Storing Data From Multiple Tables Creating Relationships Programmatically Navigating Between Tables by Using Relationships

22 [Visual C#] ordersDataAdapter = new SqlDataAdapter ("select * from Orders", connection2); customersDataAdapter.Fill(myDataSet, "Orders"); [Visual C#] ordersDataAdapter = new SqlDataAdapter ("select * from Orders", connection2); customersDataAdapter.Fill(myDataSet, "Orders"); [Visual Basic] ordersDataAdapter = new SqlDataAdapter _ ("select * from Orders", connection2) customersDataAdapter.Fill(myDataSet, "Orders") [Visual Basic] ordersDataAdapter = new SqlDataAdapter _ ("select * from Orders", connection2) customersDataAdapter.Fill(myDataSet, "Orders") Storing Data From Multiple Tables Add the first table Add the subsequent table(s) Orders Customers DataSet [Visual C#] customersDataAdapter = new SqlDataAdapter ("select * from Customers", connection1); customersDataAdapter.Fill(myDataSet, "Customers"); [Visual C#] customersDataAdapter = new SqlDataAdapter ("select * from Customers", connection1); customersDataAdapter.Fill(myDataSet, "Customers"); [Visual Basic] customersDataAdapter = new SqlDataAdapter _ ("select * from Customers", connection1) customersDataAdapter.Fill(myDataSet, "Customers") [Visual Basic] customersDataAdapter = new SqlDataAdapter _ ("select * from Customers", connection1) customersDataAdapter.Fill(myDataSet, "Customers") connection1 connection2

23 [Visual C#] DataRelation coDataRelation; DataColumn parentColumn, childColumn; parentColumn = myDataSet.Tables["Customers"].Columns["CustomerID"]; childColumn = myDataSet.Tables["Orders"].Columns["CustomerID"]; cODataRelation = new DataRelation("CustomerOrders", parentColumn, childColumn); myDataSet.Relations.Add(cODataRelation); [Visual C#] DataRelation coDataRelation; DataColumn parentColumn, childColumn; parentColumn = myDataSet.Tables["Customers"].Columns["CustomerID"]; childColumn = myDataSet.Tables["Orders"].Columns["CustomerID"]; cODataRelation = new DataRelation("CustomerOrders", parentColumn, childColumn); myDataSet.Relations.Add(cODataRelation); Creating Relationships Identify parent column Identify child column Create DataRelation Orders table Customers table DataSet parentColumn childColumn DataRelation [Visual Basic] Dim cORelation As DataRelation Dim parentColumn As DataColumn, childColumn As DataColumn parentColumn = _ myDataSet.Tables("Customers").Columns("CustomerID") childColumn = _ myDataSet.Tables("Orders").Columns("CustomerID") cODataRelation = New DataRelation("CustomerOrders" _, parentColumn, childColumn) myDataSet.Relations.Add(cODataRelation) [Visual Basic] Dim cORelation As DataRelation Dim parentColumn As DataColumn, childColumn As DataColumn parentColumn = _ myDataSet.Tables("Customers").Columns("CustomerID") childColumn = _ myDataSet.Tables("Orders").Columns("CustomerID") cODataRelation = New DataRelation("CustomerOrders" _, parentColumn, childColumn) myDataSet.Relations.Add(cODataRelation)

24 Programmatically Navigating Between Tables by Using Relationships Customers Orders GetChildRows GetParentRow DataSet [Visual Basic] ds.Tables(index).Rows(index).GetChildRows("relation") ds.Tables(index).Rows(index).GetParentRow("relation") [Visual Basic] ds.Tables(index).Rows(index).GetChildRows("relation") ds.Tables(index).Rows(index).GetParentRow("relation") [Visual C#] ds.Tables[index].Rows[index].GetChildRows("relation"); ds.Tables[index].Rows[index].GetParentRow("relation"); [Visual C#] ds.Tables[index].Rows[index].GetChildRows("relation"); ds.Tables[index].Rows[index].GetParentRow("relation");

25 Lab: Accessing Data with Microsoft ADO.NET and Visual Studio 2008 Exercise 1: Connecting to the Doctors Database Exercise 2: Paging and Selection in a GridView Control Exercise 3: Implementing a SqlDataReader Exercise 4: (If Time Permits) Viewing Doctors from All Cities Logon information Virtual machine 2310C-LON-DEV-08 User name Student Password Pa$$w0rd Estimated time: 45 minutes

26 Lab Scenario Medical medical.aspx Benefits Home Page Default.aspx Life Insurance life.aspx Retirement retirement.aspx Dentists dental.aspx Doctors doctors.aspx Logon Page login.aspx Logon Page login.aspx Registration register.aspx Registration register.aspx Prospectus prospectus.aspx XML Web Service DentalService1.asmx Page Header header.ascx Lab Web Application User Control nameDate.ascx Menu Component Benefits.cs or Benefits.vb Master Page benefitsMaster.master LINQ to SQL Classes Doctors.dbml ASPState Dentists Doctors XML Files Web. config TempDB

27 Lab Review Review Questions How can you add a connection to a database? What controls are created when you drag a table from Server Explorer to a Web page? How can you enable paging for a GridView control? How can you add a select column to a GridView control? When you use Connection and SqlDataReader objects, what must you do?

28 Module Review and Takeaways Review Questions Real-World Issues and Scenarios Best Practices


Download ppt "Developing Web Applications Using Microsoft ® Visual Studio ® 2008."

Similar presentations


Ads by Google