Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "How to use ADO.NET to write your own data access code"— Presentation transcript:

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

2 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.

3 Using Commands

4 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

5 SqlConnection

6 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

7 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();

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

9 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();

10 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);

11 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.

12 SQL Parameters. Better Way.
// 1. declare command object with parameter SqlCommand cmd = new SqlCommand("select * from Customers where city con); // 2. define parameters used in command object SqlParameter param = new SqlParameter(); param.ParameterName = //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.

13 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 A SQL Server Insert statement that uses parameters INSERT INTO Customers (Name, Address, City, State, ZipCode) @ZipCode) An OLE DB or ODBC Select statement that uses a parameter WHERE CustomerID = ?

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

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

16 Common Members of the Parameters Collections

17 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); A statement that changes the value of an existing parameter = customerID; indexer

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

19 SqlDataReader object Select

20 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

21 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();

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

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

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

25 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

26 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 SqlCommand selectCommand = new SqlCommand(selectStatement, connection); 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();

27 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) " + @ZipCode)"; SqlCommand insertCommand = new SqlCommand(insertStatement, connection); insertCommand.Parameters.AddWithValue( customer.Name); customer.Address); customer.City); customer.State); 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();

28 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 " + "Address " + "City " + "State " + "ZipCode " + "WHERE CustomerID " + "AND Name " + "AND Address " + "AND City " + "AND State " + "AND ZipCode SqlCommand updateCommand = new SqlCommand(updateStatement, connection); newCustomer.Name); newCustomer.Address); newCustomer.City); newCustomer.State); newCustomer.ZipCode); oldCustomer.CustomerID); oldCustomer.Name); oldCustomer.Address); oldCustomer.City); oldCustomer.State); 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();

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

30 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;

31 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; }

32 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();

33 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();

34 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();

35 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();

36 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();

37 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();

38 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;

39 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;

40 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;

41 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; }

42 20-1 Write the code for a Product Maintenance application

43 Project 4-5 Register products


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

Similar presentations


Ads by Google