How to use ADO.NET to write your own data access code

Slides:



Advertisements
Similar presentations
17. Data Access ADO.Net Architecture New Features of ADO.NET
Advertisements

Coding ADO.NET Objects: Connection, Command, DataReader.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
In C# program Before you can start using the ODBC class definitions, you will need to include the right module. using System.Data.Odbc; // ODBC definitions.
Chapter 9 Using the SqlDataSource Control. References aspx.
ADO.NET By Hanumantha Rao.N MCA By Hanumantha Rao.N MCA.
Chapter 7 PHP Interacts with Ms. Access (Open DataBase Connectivity (ODBC))
11 Updating a Database Table Textbook Chapter 14.
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.
Developing Web Applications Using Microsoft ® Visual Studio ® 2008.
Neal Stublen Populating a Database  SQLExpress should be installed with Visual Studio  The book provides a.sql file for populating.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.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.
Architectures Classic Client/Server Architecture Classic Web Architecture N-tier (multi-tier) Architecture FEN Databaser og Modellering.
MySQL Connection using ADO.Net Connecting to MySQL from.NET Languages.
1 Introduction to ADO.NET Microsoft ADO.NET 2.0 Step by Step Rebecca M Riordan Microsoft Press, 2006.
11 Using ADO.NET II Textbook Chapter Getting Started Last class we started a simple example of using ADO.NET operations to access the Addresses.
Sample Application Multi Layered Architecture (n-tier): –Graphical User Interface (GUI): Forms, components, controls The Visual Designer in Visual Studio.
ASP.NET Rina Zviel-Girshin Lecture 5
Neal Stublen Tonight’s Agenda  Database Errors  Parameterized queries  ToolStrip control  Master-detail relationships  Custom.
Financial Information Management Changing data in a DB Stefano Grazioli.
ADO.NET Objects – Data Providers Dr. Ron Eaglin. Requirements Visual Studio 2005 Microsoft SQL Server 2000 or 2005 –Adventure Works Database Installed.
Command Object’s ExecuteNonQuery Method ISYS 512.
1 11/10/05CS360 Windows Programming ADO.NET. 2 11/10/05CS360 Windows Programming ADO.NET  Behind every great application is a database manager o Amazon.
Presentation On How To Create Connection To A Database.
1 Avoiding Hacker Attacks. 2 Objectives You will be able to Avoid certain hacker attacks and crashes due to bad inputs from users.
Accessing Data with Microsoft Visual C# Applications.
ADO.Net CS795. What is ADO.Net? Database language spoken by managed applications ADO.net database accesses go through modules: data providers –SQL Server.Net.
HNDIT Rapid Application Development
Coding ADO.NET Objects: Connection, Command, DataReader.
Architecture Multi Layered Architecture (n-tier): Application: Model Controllers Database Access Graphical User Interface (GUI): Forms, components, controls.
DataGridView. Displaying data in a tabular format is a task you are likely to perform frequently. The DataGridView control is designed to be a complete.
Module 2: Using ADO.NET to Access Data. Overview ADO.NET Architecture Creating an Application That Uses ADO.NET to Access Data Changing Database Records.
1 Low Level ADO.NET Operations II Microsoft Visual C# 2008 Step by Step Chapter 25.
Introduction to Database C# MySQL onnect-C-to-MySQL 1.
.NET Data Access and Manipulation
Coding ADO.NET Objects: Connection, Command, DataReader.
C# MySQL onnect-C-to-MySQL 1.
Lecture Select Operation 2. Insert Operation 3. Update Operation 4. Delete Operation.
 ADO.NET is an object-oriented set of libraries that allows you to interact with data sources  Commonly, the data source is a database, but it could.
Based on Murach (ch 17) and Deitel Slides 1. o Knowledge o Describe the hardware components of a typical multi-user system. o Describe the software components.
Common SQL keywords. Building and using CASE Tools Data Base with Microsoft SQL-Server and C#
ASP.NET Programming with C# and SQL Server First Edition
Introduction to ADO.NET
ADO.NET Fundamentals.
Chapter 15 Using a Database.
Unit 9.1 Learning Objectives Data Access in Code
ADO.NET and Stored Procedures
ADO.NET Framework.
© 2013, Mike Murach & Associates, Inc.
How to Create Login Form using vb.net and SqlServer Database
Lecture 6 VB.Net SQL Server.
Databases Intro (from Deitel)
How to Create and use Classes and Structures
Unit 9.2 Database access from code Database Cycle Review
SQL commands from C# and ASP.net
ADO.Net and Stored Procedures
מתחברים למסד נתונים היכרות עם ADO.Net.
MySQL Connection using ADO.Net
Browser (Client Side) 瀏覽器 (客戶端)
How to work with bound controls and parameterized queries
E-commerce Applications Development
Based on Murach Chapter 10
How to use ADO.NET to write your own data access code
How to organize and document your classes
An introduction to database programming
PROG Advanced Web Apps 4/13/2019 Programming Data Pages Wendi Jollymore, ACES.
M S COLLEGE OF ART’S, COMM., SCI. & BMS Advance Web Programming
ADO.NET Fundamentals.
Presentation transcript:

How to use ADO.NET to write your own data access code Based on Murach C# 2015 Chapter 20

Objectives Applied Use a connection to access a SQL Server database. Use a data reader to retrieve data from a database. Use data commands to execute action queries or queries that return a scalar value. Use parameters to limit the data that’s processed by a data command. Knowledge Describe the use of parameters with SQL statements. Describe the use of a data reader. Describe the use of the two types of queries that don’t return result sets.

Using Commands

Connections, Commands, DataReaders The canonical usage pattern for executing database commands in ADO.Net: Step1. Create a connection object encapsulating a connection string Step 2. Open the connection by calling Open on the connection object Step 3. Create a command object encapsulating both 1. an SQL command 2. and the connection that the command will use Step. 4. Call a method on the command object to execute the command Step. 5. Close the connection by calling Close on the connection object

SqlConnection

Three connection strings for the SQL Server provider For a SQL Server Express LocalDB database Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Databases\\MMABooks.mdf; Integrated Security=True When included in project Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\MMABooks.mdf; A connection string for a SQL Server Express database Data Source=localhost\\SqlExpress;Initial Catalog=MMABooks;Integrated Security=True A connection string for the Jet OLE DB provider Provider=Microsoft.Jet.OLEDB.4.0;DataSource=C:\\Databases\\MMABooks.mdb

Code that creates, opens, and closes a SQL connection string connectionString = "Data Source=localhost\\SqlExpress;" + "Initial Catalog=MMABooks;Integrated Security=True"; SqlConnection connection = new SqlConnection(connectionString); connection.Open(); … //Do all your the work here connection.Close();

Three constructors for the SqlCommand class new SqlCommand() new SqlCommand(commandText) new SqlCommand(commandText, connection)

SqlCommand.ExecuteScalar Method Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored. Ex.: cmd.CommandText = "SELECT COUNT(*) FROM dbo.region"; Int count = (Int32)cmd.ExecuteScalar();

Code that creates a SqlCommand object that executes a Select statement SqlConnection connection = new SqlConnection(connectionString); string selectStatement = "SELECT CustomerID, Name, Address, City, State, ZipCode " + "FROM Customers"; SqlCommand selectCommand = new SqlCommand(selectStatement, connection);

SQL Parameters. Why? // Bad Idea SqlCommand cmd = new SqlCommand("select * from Customers where city = '" + inputCity + "'"; Anything placed into that TextBox will be put into inputCity and added to this SQL string. This situation invites a hacker to replace that string with something malicious string. In the worst case scenario, you could give full control of your computer away.

SQL Parameters. Better Way. // 1. declare command object with parameter SqlCommand cmd = new SqlCommand("select * from Customers where city = @City", con); // 2. define parameters used in command object SqlParameter param = new SqlParameter(); param.ParameterName = "@City"; //same spelling param.Value = inputCity; // 3. add new parameter to command object cmd.Parameters.Add(param); // get data stream reader = cmd.ExecuteReader(); Parameters are treated as literal values and not as executable code. Also, the parameter is checked for type and length. If the data does not conform to the type or length defined by the parameter, the SqlParameter class throws an exception.

SQL Parameters SQLParameter Class Represents a parameter to a SqlCommand and optionally its mapping to DataSet columns. This class cannot be inherited. A SQL Server Select statement that uses a parameter SELECT CustomerID, Name, Address, City, State, ZipCode FROM Customers WHERE CustomerID = @CustomerID A SQL Server Insert statement that uses parameters INSERT INTO Customers (Name, Address, City, State, ZipCode) VALUES (@Name, @Address, @City, @State, @ZipCode) An OLE DB or ODBC Select statement that uses a parameter WHERE CustomerID = ?

Four constructors for the SqlParameter class new SqlParameter() new SqlParameter(name, value) new SqlParameter(name, type) new SqlParameter(name, type, size)

Typical Code that creates a parameter SqlParameter customerIDParm = new SqlParameter(); customerIDParm.ParameterName = "@CustomerID"; customerIDParm.Value = customerID; Another way to create a parameter SqlParameter customerIDParm = new SqlParameter("@CustomerID", customerID);

Common Members of the Parameters Collections

Using Parameters Collections A statement that adds a parameter to the Parameters collection selectCommand.Parameters.Add(customerIDParm); A statement that creates a parameter and adds it to the Parameters collection selectCommand.Parameters.AddWithValue( "@CustomerID", customerID); A statement that changes the value of an existing parameter selectCommand.Parameters["@CustomerID"].Value = customerID; indexer

SqlDataReader object Two ways to create a SqlDataReader object sqlCommand.ExecuteReader() sqlCommand.ExecuteReader(behavior) Common CommandBehavior enumeration members CloseConnection Default SingleRow

SqlDataReader object Select

Example of Code that uses a data reader to read a list of State objects connection.Open(); SqlDataReader reader = selectCommand.ExecuteReader( CommandBehavior.CloseConnection); List<State> states = new List<State>(); while (reader.Read()) { State s = new State(); s.StateCode = reader["StateCode"].ToString(); s.StateName = reader["StateName"].ToString(); states.Add(s); } reader.Close(); Closes connection when reader is closed

Already Covered. Code that creates and executes a command that returns an aggregate (blob) (Scalar) value string selectStatement = "SELECT SUM(InvoiceTotal) FROM Invoices"; SqlCommand selectCommand = new SqlCommand(selectStatement, connection); connection.Open(); decimal invoiceTotal = (decimal) selectCommand.ExecuteScalar; connection.Close();

Code that creates and executes a command that inserts a row Step 1. string insertStatement = "INSERT Products " + "(ProductCode, Description, UnitPrice) " + "VALUES (@ProductCode, @Description, @UnitPrice)"; Step 2. SqlCommand insertCommand = new SqlCommand(insertStatement, connection); Step 3. insertCommand.Parameters.AddWithValue("@ProductCode", product.Code); insertCommand.Parameters.AddWithValue("@Description", product.Description); insertCommand.Parameters.AddWithValue("@UnitPrice", product.Price); Step 4. try { connection.Open(); int productCount = insertCommand.ExecuteNonQuery(); } catch (SqlException ex) MessageBox.Show(ex.Message); finally { connection.Close();

The Customer Maintenance form Not ToolStrip The Customer Maintenance form The Add/Modify Customer form

The dialog box that’s displayed to confirm a delete operation

Some irrelevant classes are not shown The class diagram (In Solution Explorer or Class View, right-click the project and choose View, then choose View Class Diagram.)* Some irrelevant classes are not shown

The code for the CustomerDB class (GetCustomer) public static class CustomerDB { public static Customer GetCustomer(int customerID) SqlConnection connection = MMABooksDB.GetConnection(); string selectStatement = "SELECT CustomerID, Name, Address, City, State, ZipCode " + "FROM Customers " + "WHERE CustomerID = @CustomerID"; SqlCommand selectCommand = new SqlCommand(selectStatement, connection); selectCommand.Parameters.AddWithValue("@CustomerID", customerID); try connection.Open(); SqlDataReader custReader = selectCommand.ExecuteReader(CommandBehavior.SingleRow); if (custReader.Read()) Customer customer = new Customer(); customer.CustomerID = (int)custReader["CustomerID"]; customer.Name = custReader["Name"].ToString(); customer.Address = custReader["Address"].ToString(); customer.City = custReader["City"].ToString(); customer.State = custReader["State"].ToString(); customer.ZipCode = custReader["ZipCode"].ToString(); return customer; } else return null; catch (SqlException ex) throw ex; finally connection.Close();

The code for the CustomerDB class (AddCustomer) public static int AddCustomer(Customer customer) { SqlConnection connection = MMABooksDB.GetConnection(); string insertStatement = "INSERT Customers " + "(Name, Address, City, State, ZipCode) " + "VALUES (@Name, @Address, @City, @State, @ZipCode)"; SqlCommand insertCommand = new SqlCommand(insertStatement, connection); insertCommand.Parameters.AddWithValue( "@Name", customer.Name); "@Address", customer.Address); "@City", customer.City); "@State", customer.State); "@ZipCode", customer.ZipCode); try connection.Open(); insertCommand.ExecuteNonQuery(); string selectStatement = "SELECT IDENT_CURRENT('Customers') FROM Customers"; SqlCommand selectCommand = new SqlCommand(selectStatement, connection); int customerID = Convert.ToInt32(selectCommand.ExecuteScalar()); return customerID; } catch (SqlException ex) throw ex; finally connection.Close();

The code for the CustomerDB class (UpdateCustomer) public static bool UpdateCustomer(Customer oldCustomer, Customer newCustomer){ SqlConnection connection = MMABooksDB.GetConnection(); string updateStatement = "UPDATE Customers SET " + "Name = @NewName, " + "Address = @NewAddress, " + "City = @NewCity, " + "State = @NewState, " + "ZipCode = @NewZipCode " + "WHERE CustomerID = @oldCustomerID " + "AND Name = @OldName " + "AND Address = @OldAddress " + "AND City = @OldCity " + "AND State = @OldState " + "AND ZipCode = @OldZipCode"; SqlCommand updateCommand = new SqlCommand(updateStatement, connection); updateCommand.Parameters.AddWithValue("@NewName", newCustomer.Name); updateCommand.Parameters.AddWithValue("@NewAddress", newCustomer.Address); updateCommand.Parameters.AddWithValue("@NewCity", newCustomer.City); updateCommand.Parameters.AddWithValue("@NewState", newCustomer.State); updateCommand.Parameters.AddWithValue("@NewZipCode", newCustomer.ZipCode); updateCommand.Parameters.AddWithValue("@OldCustomerID", oldCustomer.CustomerID); updateCommand.Parameters.AddWithValue("@OldName", oldCustomer.Name); updateCommand.Parameters.AddWithValue("@OldAddress", oldCustomer.Address); updateCommand.Parameters.AddWithValue("@OldCity", oldCustomer.City); updateCommand.Parameters.AddWithValue("@OldState", oldCustomer.State); updateCommand.Parameters.AddWithValue("@OldZipCode", oldCustomer.ZipCode); try{ connection.Open(); int count = updateCommand.ExecuteNonQuery(); if (count > 0) return true; else return false; }catch (SqlException ex){ throw ex; } finally{ connection.Close();

The code for the CustomerDB class (DeleteCustomer) public static bool DeleteCustomer(Customer customer) { SqlConnection connection = MMABooksDB.GetConnection(); string deleteStatement = "DELETE FROM Customers " + "WHERE CustomerID = @CustomerID " + "AND Name = @Name " + "AND Address = @Address " + "AND City = @City " + "AND State = @State " + "AND ZipCode = @ZipCode"; SqlCommand deleteCommand = new SqlCommand(deleteStatement, connection); deleteCommand.Parameters.AddWithValue("@CustomerID", customer.CustomerID); deleteCommand.Parameters.AddWithValue("@Name", customer.Name); deleteCommand.Parameters.AddWithValue("@Address", customer.Address); deleteCommand.Parameters.AddWithValue("@City", customer.City); deleteCommand.Parameters.AddWithValue("@State", customer.State);"@ZipCode",customer.ZipCode); try { connection.Open(); int count = deleteCommand.ExecuteNonQuery(); if (count > 0) return true; else return false; } catch (SqlException ex) throw ex; finally connection.Close();

The code for the StateDB class public static class StateDB { public static List<State> GetStates() List<State> states = new List<State>(); SqlConnection connection = MMABooksDB.GetConnection(); string selectStatement = "SELECT StateCode, StateName " + "FROM States " + "ORDER BY StateName"; SqlCommand selectCommand = new SqlCommand(selectStatement, connection); try connection.Open(); SqlDataReader reader = selectCommand.ExecuteReader(); while (reader.Read()) State s = new State(); s.StateCode = reader["StateCode"].ToString(); s.StateName = reader["StateName"].ToString(); states.Add(s); } reader.Close(); catch (SqlException ex) throw ex; finally connection.Close(); return states;

The code for the MMABooksDB class public static class MMABooksDB { public static SqlConnection GetConnection() string connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\MMABooks.mdf;" + "Integrated Security=True"; SqlConnection connection = new SqlConnection(connectionString); return connection; }

The Customer Maintenance form public partial class frmCustomerMaintenance : Form { public frmCustomerMaintenance() InitializeComponent(); } private Customer customer; private void btnGetCustomer_Click(object sender, EventArgs e) if (Validator.IsPresent(txtCustomerID) && Validator.IsInt32(txtCustomerID)) int customerID = Convert.ToInt32(txtCustomerID.Text); this.GetCustomer(customerID); if (customer == null) MessageBox.Show("No customer found with this ID. " + "Please try again.", "Customer Not Found"); this.ClearControls(); else this.DisplayCustomer();

The Customer Maintenance form (cont.) private void GetCustomer(int customerID) { try customer = CustomerDB.GetCustomer(customerID); } catch (Exception ex) MessageBox.Show(ex.Message, ex.GetType().ToString()); private void ClearControls() txtCustomerID.Text = ""; txtName.Text = ""; txtAddress.Text = ""; txtCity.Text = ""; txtState.Text = ""; txtZipCode.Text = ""; btnModify.Enabled = false; btnDelete.Enabled = false; txtCustomerID.Focus();

The Customer Maintenance form (cont.) private void DisplayCustomer() { txtName.Text = customer.Name; txtAddress.Text = customer.Address; txtCity.Text = customer.City; txtState.Text = customer.State; txtZipCode.Text = customer.ZipCode; btnModify.Enabled = true; btnDelete.Enabled = true; } private void btnAdd_Click(object sender, EventArgs e) frmAddModifyCustomer addCustomerForm = new frmAddModifyCustomer(); addCustomerForm.addCustomer = true; DialogResult result = addCustomerForm.ShowDialog(); if (result == DialogResult.OK) customer = addCustomerForm.customer; txtCustomerID.Text = customer.CustomerID.ToString(); this.DisplayCustomer();

The Customer Maintenance form (cont.) private void btnModify_Click(object sender, EventArgs e) { frmAddModifyCustomer modifyCustomerForm = new frmAddModifyCustomer(); modifyCustomerForm.addCustomer = false; modifyCustomerForm.customer = customer; DialogResult result = modifyCustomerForm.ShowDialog(); if (result == DialogResult.OK) customer = modifyCustomerForm.customer; this.DisplayCustomer(); } else if (result == DialogResult.Retry) this.GetCustomer(customer.CustomerID); if (customer != null) else this.ClearControls();

The Customer Maintenance form (cont.) private void btnDelete_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show("Delete " + customer.Name + "?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) try if (! CustomerDB.DeleteCustomer(customer)) MessageBox.Show("Another user has updated or deleted " + "that customer.", "Database Error"); this.GetCustomer(customer.CustomerID); if (customer != null) this.DisplayCustomer(); else this.ClearControls(); } catch (Exception ex) MessageBox.Show(ex.Message, ex.GetType().ToString()); private void btnExit_Click(object sender, EventArgs e) this.Close();

The Add/Modify Customer form public partial class frmAddModifyCustomer : Form { public frmAddModifyCustomer() InitializeComponent(); } public bool addCustomer; public Customer customer; private void frmAddModifyCustomer_Load(object sender, EventArgs e) this.LoadStateComboBox(); if (addCustomer) this.Text = "Add Customer"; cboStates.SelectedIndex = -1; else this.Text = "Modify Customer"; this.DisplayCustomer();

The Add/Modify Customer form private void LoadStateComboBox() { List<State> states = new List<State>(); try states = StateDB.GetStates(); cboStates.DataSource = states; cboStates.DisplayMember = "StateName"; cboStates.ValueMember = "StateCode"; } catch (Exception ex) MessageBox.Show(ex.Message, ex.GetType().ToString()); private void DisplayCustomer() txtName.Text = customer.Name; txtAddress.Text = customer.Address; txtCity.Text = customer.City; cboStates.SelectedValue = customer.State; txtZipCode.Text = customer.ZipCode;

The Add/Modify Customer form private void btnAccept_Click(object sender, EventArgs e) { if (IsValidData()) if (addCustomer) customer = new Customer(); this.PutCustomerData(customer); try customer.CustomerID = CustomerDB.AddCustomer(customer); this.DialogResult = DialogResult.OK; } catch (Exception ex) MessageBox.Show(ex.Message, ex.GetType().ToString()); else Customer newCustomer = new Customer(); newCustomer.CustomerID = customer.CustomerID; this.PutCustomerData(newCustomer); if (! CustomerDB.UpdateCustomer(customer, newCustomer)) MessageBox.Show("Another user has updated or " + "deleted that customer.", "Database Error"); this.DialogResult = DialogResult.Retry; customer = newCustomer;

The Add/Modify Customer form private bool IsValidData() { return Validator.IsPresent(txtName) && Validator.IsPresent(txtAddress) && Validator.IsPresent(txtCity) && Validator.IsPresent(cboStates) && Validator.IsPresent(txtZipCode); } private void PutCustomerData(Customer customer) customer.Name = txtName.Text; customer.Address = txtAddress.Text; customer.City = txtCity.Text; customer.State = cboStates.SelectedValue.ToString(); customer.ZipCode = txtZipCode.Text;

The Add/Modify Customer form (cont.) private void PutCustomerData(Customer customer) { customer.Name = txtName.Text; customer.Address = txtAddress.Text; customer.City = txtCity.Text; customer.State = cboStates.SelectedValue.ToString(); customer.ZipCode = txtZipCode.Text; }

20-1 Write the code for a Product Maintenance application

Project 4-5 Register products