Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Chapter 14


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Chapter 14

  1. 1. • Understanding Databases• Configuring, Browsing & Modifying Databases in Visual Studio• SQL Basics• The Data Provider Model• Direct Data Access • Creating Connection • Select, Insert, Delete, Update Records• Disconnected Data Access • Selecting Multiple Tables • Defining Relationships
  2. 2. The most common way to manage data is to use adatabase. A typical web application is oftenjust a thin user interface shell on top ofsophisticated data-driven code that reads andwrites information from a database.In a relational database model information isstored in the form of tables. SQL Server, Oracle,and Microsoft Access are examples of relationaldatabase management system.
  3. 3. If you‟re using a full version of SQL Server, you‟ll probablyuse a graphical tool such as SQL Server ManagementStudio to create and manage your databases.You can perform many of the same tasks using VisualStudio‟s Server Explorer Window. Click View ➤ ServerExplorer to show it. Using the Data Connections node inthe Server Explorer, you can connect to existingdatabases or create new ones.Right-click the Data Connections node, and choose AddConnection. If the Choose Data Source window appears,select Microsoft SQL Server and then click Continue.
  4. 4. SELECT [columns] FROM [tables] WHERE [search_condition]ORDER BY [order_expression ASC | DESC]SELECT au_lname, au_fname FROM Authors WHERE State=CAORDER BY au_lname ASCSELECT * FROM Sales WHERE ord_date < 2000/01/01 ANDord_date > 1987/01/01„SELECT * FROM Stores WHERE stor_name LIKE B%„ or „%S‟SELECT COUNT(*) FROM AuthorsUPDATE Authors SET phone=408 496-2222 WHERE au_id=172-32-1176„INSERT INTO Authors (au_id, au_lname, au_fname, zip, contract)VALUES (998-72-3566, Khan, John, 84152, 0)DELETE FROM Authors WHERE au_id=172-32-1176
  5. 5. ADO.NET relies on the functionality in a small set ofcore classes.You can divide these classes into two groups:Data Containers that are used to contain and managedata (such as DataSet, DataTable, DataRow, andDataRelation)Data Providers that are used to connect to a specificdata source (such as Connection, Command, andDataReader).
  6. 6. The SQL Server data provider is designed to work withSQL Server. The classes you‟ll use fall into three keynamespaces
  7. 7. The most straightforward way to interact with a databaseis to use direct data access. You use commands toquery, insert, update, and delete information.When you query data with direct data access, you don‟tkeep a copy of the information in memory. Instead, youwork with it for a brief period of time while the databaseconnection is open, and then close the connection assoon as possible.The direct data model is well suited to ASP.NET webpages, which don‟t need to keep a copy of their data inmemory for long periods of time because a pagetypically has a lifetime of only a few seconds.
  8. 8. 1. Create Connection, Command, and DataReader objects.2. Use the DataReader to retrieve information from the database, and display it in a control on a web form.3. Close your connection.4. Send the page to the user. At this point, the information your user sees and the information in the database no longer have any connection, and all the ADO.NET objects have been destroyed.To add or update information, follow these steps:1. Create new Connection and Command objects.2. Execute the Command (with the appropriate SQL statement).
  9. 9. Before you can retrieve or update data, you need tomake a connection to the data source.Generally, connections are limited to some fixed number,and if you exceed that number (either because you runout of licenses or because your database server can‟taccommodate the user load), attempts to create newconnections will fail. For that reason, you should try tohold a connection open for as short a time as possible.You should also write your database code inside atry/catch error handling structure so you can respond ifan error does occur, and make sure you close theconnection even if you can‟t perform all your work.
  10. 10. When creating a Connection object, you need to specify avalue for its ConnectionString property. This ConnectionStringdefines all the information the computer needs to find the datasource, log in, and choose an initial database.SqlConnection myConnection = new SqlConnection();myConnection.ConnectionString = "Data Source=localhost;" +"Initial Catalog=Pubs;Integrated Security=SSPI";You can connect directly to any database file, even ifit‟s not in the master list of databasesmyConnection.ConnectionString = @"Data Source=localhostSQLEXPRESS;" + @"User Instance =True;AttachDBFilename= |DataDirectory|Northwind.mdf;" +"Integrated Security=True";|DataDirectory| automatically points to the App_Data folder
  11. 11. Initial catalog: This is the name of the database that this connection willbe accessing. It’s only the “initial” database because you can change itlater by using the Connection.ChangeDatabase() method.Integrated security: This indicates you want to connect to SQL Serverusing the Windows user account that‟s running the web page code,provided you supply a value of SSPI (which stands for Security SupportProvider Interface). Alternatively, you can supply a user ID andpassword that‟s defined in the database for SQL Server authentication,although this method is less secure and generally discouraged.ConnectionTimeout: This determines how long your code will wait, inseconds, before generating an error if it cannot establish a databaseconnection. Our example connection string doesn‟t set theConnectionTimeout, so the default of 15 seconds is used. You can use0 to specify no limit, but this is a bad idea. This means that,theoretically, the code could be held up indefinitely while it attemptsto contact the server.
  12. 12. <configuration><connectionStrings><add name="Pubs" connectionString="Data Source=localhost;Initial Catalog=Pubs;IntegratedSecurity=SSPI"/></connectionStrings>...</configuration>string connectionString =WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString;SqlConnection myConnection = newSqlConnection(connectionString);
  13. 13. string connectionString =WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString;SqlConnection myConnection = new SqlConnection(connectionString);try {myConnection.Open();lblInfo.Text = "<b>Server Version:</b> " + myConnection.ServerVersion;lblInfo.Text += "<br /><b>Connection Is:</b> " +myConnection.State.ToString();}catch (Exception err){// Handle an error by displaying the information.lblInfo.Text = "Error reading the database. ";lblInfo.Text += err.Message;}finally{myConnection.Close();lblInfo.Text += "<br /><b>Now Connection Is:</b> ";lblInfo.Text += myConnection.State.ToString();}
  14. 14. string connectionString =WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString;SqlConnection myConnection = new SqlConnection(connectionString);try {using (myConnection){// Try to open the connection.myConnection.Open();lblInfo.Text = "<b>Server Version:</b> " + myConnection.ServerVersion;lblInfo.Text += "<br /><b>Connection Is:</b> " +myConnection.State.ToString();} }catch (Exception err){// Handle an error by displaying the information.lblInfo.Text = "Error reading the database. ";lblInfo.Text += err.Message;}lblInfo.Text += "<br /><b>Now Connection Is:</b> ";lblInfo.Text += myConnection.State.ToString();
  15. 15. string selectSQL = "SELECT au_lname, au_fname, au_id FROM Authors";SqlConnection con = new SqlConnection(connectionString);SqlCommand cmd = new SqlCommand(selectSQL, con);SqlDataReader reader;try{con.Open();reader = cmd.ExecuteReader(); while (reader.Read()) { ListItem newItem = new ListItem(); newItem.Text = reader["au_lname"] + ", " + reader["au_fname"]; newItem.Value = reader["au_id"].ToString(); lstAuthor.Items.Add(newItem);}reader.Close(); }catch (Exception err) {lblResults.Text = "Error reading list of names. ";lblResults.Text += err.Message; }finally{con.Close();}
  16. 16. When you use disconnected data access, you keep a copy ofyour data in memory using the DataSet. You connect to thedatabase just long enough to fetch your data and dump it intothe DataSet, and then you disconnect immediately.Reasons to use the DataSet to hold onto data in memory:• You need to do something time-consuming with the data• You want to use ASP.NET data binding to fill a web control (like a GridView) with your data.• You want to navigate backward and forward through your data while you‟re processing it.• You want to navigate from one table to another.• You want to save the data to a file for later use.