27
Web Server Programming Direct Data Access, Data Binding

Web Server Programming

  • Upload
    kizzy

  • View
    36

  • Download
    1

Embed Size (px)

DESCRIPTION

Web Server Programming. Direct Data Access, Data Binding. Content. Direct Data Access Data Binding. Direct Data Access. Important Note!!!. Last week, you learned how to connect to databases using built-in controls. Use them in your applications whenever possible. - PowerPoint PPT Presentation

Citation preview

Web Server Programming

Web Server ProgrammingDirect Data Access, Data BindingContentDirect Data AccessData BindingMuzaffer DOAN - Anadolu University2Direct Data AccessMuzaffer DOAN - Anadolu University3Important Note!!!Last week, you learned how to connect to databases using built-in controls.Use them in your applications whenever possible.If you sure that you need to connect to database manually, follow the instructions explained in this class.Muzaffer DOAN - Anadolu University4Direct Data Access QueryingCreate Connection, Command, and DataReader objectsUse the DataReader to retrieve information from the database, and display it in a controlClose your connectionSend the page to the userMuzaffer DOAN - Anadolu University5Updating, Inserting, DeletingCreate new Connection and Command objectsExecute the Command with the appropriate SQL statementMuzaffer DOAN - Anadolu University6Direct Data Access with ADO.NETMuzaffer DOAN - Anadolu University7

ADO.NET Data Provider ClassesSQL ServerOleDB (Access)ConnectionSqlConnectionOleDbConnectionCommandSqlCommandOleDbCommandDataReaderSqlDataReaderOleDbDataReaderDataAdapterSqlDataAdapterOleDbDataAdapterMuzaffer DOAN - Anadolu University8Use OracleConnection, OracleCommand, etc. for Oracle data providersUse OdbcConnection, OdbcCommand, etc. for ODBC data providersNamespace ImportsImport following namespaces for SQL Server:using System.Data;using System.Data.SqlClient;Import following namespaces for Access:using System.Data;using System.OleDb;Muzaffer DOAN - Anadolu University9Connecting Access DatabaseOleDbConnection conn = new OleDbConnection();

conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Survey.mdb";

conn.Open();

// Database operations will be here...

conn.Close();Muzaffer DOAN - Anadolu University10Connecting SQL Server ExpressSqlConnection conn = new SqlConnection();

conn.ConnectionString = @"Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\Survey.mdf; Integrated Security=True;User Instance=True";

conn.Open();

// Database operations will be here...

conn.Close();Muzaffer DOAN - Anadolu University11How to Obtain Connection StringsUse SqlDataSource or AccessDataSource objects to connect to the database and copy the connection strings into your codehttp://www.connectionstrings.com shows many connection string optionsMuzaffer DOAN - Anadolu University12Storing the Connection StringWrite the connection string into connectionString section of web.config file:

...

Muzaffer DOAN - Anadolu University13Retrieving the Connection Stringstring connectionString = WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString;Muzaffer DOAN - Anadolu University14Execute CommandCommand object has several methods starting with the "Execute" string:ExecuteNonQuery(): Used for queries that don't return any records (e.g. Update, Insert, Delete queries)ExecuteReader(): Used for queries that return one or more records (e.g. Select query)ExecuteScalar(): Used for queries that return one or more records but this method returns only the first column of the first row (suitable for obtaining number of records, maximum value of a column)Muzaffer DOAN - Anadolu University15The DataReaderAllows you to quickly retrieve all your resultsUses a live connection and should be used quickly and then closedCan retrieve only one record at a timeSupports fast-forward-only and read-only access to the results (previous record cannot be reached)Provides better performance than the DataSetMuzaffer DOAN - Anadolu University16The DataReaderCreate a DataReader by ExecuteReader method of the Command objectRetrieve the record by the Read() method of the DataReader objectTo retrieve the next record, use Read() method againIf next record is successfully read, the Read() method returns trueSo, continue reading until the Read() method returns falseMuzaffer DOAN - Anadolu University17The DataReaderOleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Survey.mdb");OleDbCommand cmd = new OleDbCommand("SELECT * FROM UserInfo", conn);conn.Open();OleDbDataReader reader = cmd.ExecuteReader();while (reader.Read()){ Label1.Text += reader["FirstName"] + "
";}reader.Close();conn.Close();Muzaffer DOAN - Anadolu University18ExecuteScalar ExampleOleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Survey.mdb");OleDbCommand cmd = new OleDbCommand("SELECT MAX(FavoriteNumber) FROM UserInfo", conn);conn.Open();

int maxfav = (int)cmd.ExecuteScalar();

conn.Close();Muzaffer DOAN - Anadolu University19ExecuteNonQuery ExampleOleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Survey.mdb");OleDbCommand cmd = new OleDbCommand("DELETE * FROM UserInfo WHERE UserID=5", conn);conn.Open();

int affectedRowNumber = cmd.ExecuteNonQuery();

conn.Close();Muzaffer DOAN - Anadolu University20Data BindingMuzaffer DOAN - Anadolu University21Data BindingYou can use the DataSet or the DataReader to retrieve rows of information, format them individually, and add them to an HTML table on a web pageConceptually, this isnt too difficult. However, it still requires a lot of repetitive code to move through the data, format columns, and display it in the correct orderRepetitive code may be easy, but its also error-prone, difficult to enhance, and unpleasant to readFortunately, ASP.NET adds a feature that allows you to skip this process and pop data directly into HTML elements and fully formatted controls. Its called data bindingMuzaffer DOAN - Anadolu University22Data BindingThe basic principle of data binding is this: you tell a control where to find your data and how you want it displayed, and the control handles the rest of the details.ASP.NET data binding works in one direction only. Information moves from a data object into a control. Then the data objects are thrown away, and the page is sent to the client. If the user modifies the data in a data-bound control, your program can update the corresponding record in the database, but nothing happens automatically.Muzaffer DOAN - Anadolu University23Types of ASP.NET Data BindingSingle-Value, or "Simple", Data BindingSingle-value data binding allows you to take a variable, a property, or an expression and insert it dynamically into a pageSingle-value binding also helps you create templates for the rich data controlsRepeated-Value, or "List", BindingAllows you to display an entire table (or just a single field from a table)Muzaffer DOAN - Anadolu University24Using Data BindingTo use single-value binding, you must insert a data binding expression into the markup in the .aspx file (not the code-behind file).To use repeated-value binding, you must set one or more properties of a data control.Once you specify data binding, you need to activate it. You accomplish this task by calling the DataBind() method of the control.Alternatively, you can bind the whole page at once by calling the DataBind() method of the current Page object.Muzaffer DOAN - Anadolu University25A Simple List Binding ExampleArrayList fruit = new ArrayList();fruit.Add("Kiwi");fruit.Add("Mango");fruit.Add("Blueberry");fruit.Add("Apricot");fruit.Add("Banana");lstItems.DataSource = fruit;lstItems.DataBind(); // orthis.DataBind();Muzaffer DOAN - Anadolu University26ReferencesBeginning ASP.NET 3.5 in C# 2008: From Novice to ProfessionalVisual Studio and MSDN HelpMuzaffer DOAN - Anadolu University27