Download presentation
Presentation is loading. Please wait.
Published byYulia Sutedja Modified over 5 years ago
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
Basic ActiveX Data Object (ADO.NET ) components (ch 17)
L I C T O N Data used by apps MS SQL Oracle DB2 Excel …
4
Different Presentation (ch 17)
From ~dbock/cmis142/WebNotes/Ch10Notes/10-databases_files/image006.jpg From
5
Now: Using Commands
6
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
7
SqlConnection You can set the ConnectionString property after you create a connection or as you create it by passing the string to the constructor of the connection class. The values you specify for the ConnectionString property depend on the type of database you’re connecting to.
8
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
9
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();
10
Three constructors for the SqlCommand class
new SqlCommand() new SqlCommand(commandText) new SqlCommand(commandText, connection)
11
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);
12
CommandText The CommandText and Connection properties are set to the values you pass to the constructor of the command Class. If you don’t pass these values to the constructor, you must set the CommandText and Connection properties after you create the command object. If you set the CommandText property to the name of a stored procedure, you must set the CommandType property to StoredProcedure.
13
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.
14
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.
15
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 = ?
16
Parameter A parameter lets you place variable information into a SQL statement. When you use a parameter in the Where clause of a Select statement, the resulting query is often called a parameterized query because the results of the query depend on the values of the parameters. You can also use parameters in Insert or Update statements to provide the values for the database row or rows to be inserted or updated. Likewise, you can use parameters in a Delete statement to indicate which row or rows should be deleted. To use parameters, you code a SQL statement with placeholders for the parameters. Then, you create a parameter object that defines each parameter, and you add it to the Parameters collection of the command object that contains the SQL statement. The placeholder for a parameter in a SQL Server command is a variable whose name begins with an at sign In most cases, you’ll give the variable the same name as the column it’s associated with. If you’re using the OLE DB or ODBC provider, you code the placeholder for a parameter as a question mark. The question mark simply indicates the position of the parameter.
17
Four constructors for the SqlParameter class
new SqlParameter() new SqlParameter(name, value) new SqlParameter(name, type) new SqlParameter(name, type, size) docs.microsoft.com/en-us/dotnet/api/system.data.sqldbtype?view=netframework-4.7.2
18
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); Simple and good example is here
19
Common Members of the Parameters Collections
20
Parameter Name, Value, Type, Size
When you create a parameter, you can specify the parameter name along with a value, a data type, or a data type and size. If you don’t specify the appropriate values, you can set the values of the associated properties after you create the parameter. In addition to a name, you must set the value for a parameter before you can use it. However, the type and size can be inferred from the value. When you create parameters for a SQL Server command, you must give them the same names you used in the SQL statement since ADO.NET refers to them by name. Because the parameters for an OLE DB or ODBC command aren’t named in the SQL statement, the parameters can be given any name you want.
21
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
22
SqlDataReader object Two ways to create a SqlDataReader object
sqlCommand.ExecuteReader() sqlCommand.ExecuteReader(behavior) Common CommandBehavior enumeration members CloseConnection Default SingleRow
23
SqlDataReader object Select
24
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
25
Select = Read To execute a command that contains a Select statement that returns a result set, you use the ExecuteReader method. This method executes the Select statement and creates a data reader object. Then, you can use the properties and methods of the data reader to work with the result set. When you execute the ExecuteReader method, you can use the CommandBehavior enumeration to specify a behavior. You can use these members to simplify your code or to improve the efficiency of your application. After you create a data reader, you use the Read method to retrieve the next row of data in the result set. Note that you must also execute the Read method to retrieve the first row of data. It’s not retrieved automatically when the data reader is created. To access a column from the most recently retrieved row, you can use the column name as an indexer. You can also specify a column by its position in the row by using an integer indexer. For example, since the first column in the States table is named StateCode, you can supply “StateCode” or zero as the indexer fora reader to retrieve the data for that column.
26
Select = Read cont. First, the connection that’s used by the SqlCommand object is opened. This command contains a Select statement that retrieves all the data from the States table. Then, the ExecuteReader method is used to retrieve that data and create a data reader that can process the state rows. Because the CloseConnection behavior is included on this method, the connection will be closed automatically when the data reader is closed. The ExecuteReader method also opens the data reader and positions it before the first row in the result set. Next, a List<> object that can hold State objects is created, and a while statement is used to loop through the rows in the result set. The condition on the while statement executes the Read method of the data reader. This works because the Read method returns a Boolean value that indicates whether the result set contains additional rows. As long as this condition is true, the program processes the row that was retrieved. In this case, the program creates a State object for each row in the States table and adds it to the List<> object. After all of the rows have been processed, the data reader is closed.
27
Scalar Value Commands that return a single value, called a scalar value. To do that, you use the ExecuteScalar method of the command. In the example, the command contains a Select statement that retrieves a sum of the invoice totals in the Invoices table. This type of summary value is often called an aggregate value. A scalar value can also be the value of a single column, a calculated value, or any other value that can be retrieved from the database. Since the ExecuteScalar method returns an Object type, you must cast that object to an appropriate data type to get its value. In this example, the object is cast to a decimal value. You can use the ExecuteScalar method with a Select statement that retrieves more than one value. In that case, though, the ExecuteScalar method returns only the first value and the others are discarded.
28
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();
29
Another example 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();
30
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();
31
Customer Maintenance: The dialog box that’s displayed to confirm a delete operation
32
The Customer Maintenance form (multiple forms)
No ToolStrip The Add/Modify Customer form
33
Add, Modify, Delete Customer
To add a customer, the user clicks the Add button on the Customer Maintenance form to display a blank Add Customer form. Then, the user enters the data for the new customer and clicks the Accept button to return to the Customer Maintenance form. To modify the data for an existing customer, the user enters the customer ID and clicks the Get Customer button to display the information for that customer. Then, the user clicks the Modify button to display the Modify Customer form, makes the appropriate modifications, and clicks the Accept button to return to the CustomerMaintenance form. To delete a customer, the user enters the customer ID and clicks the Get Customer button to display the information for that customer. Then, the user clicks the Delete button and responds to the dialog box that’s displayed to confirm the delete operation.
34
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 *May not be available in VS Community Edition by default
35
Important: 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();
36
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();
37
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();
38
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();
39
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;
40
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; }
41
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();
42
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();
43
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();
44
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();
45
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();
46
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();
47
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;
48
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;
49
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;
50
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; }
51
20-1 Write the code for a Product Maintenance application
52
Project 4-5 Register products
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.