Presentation is loading. Please wait.

Presentation is loading. Please wait.

Unit 9.1 Learning Objectives Data Access in Code

Similar presentations


Presentation on theme: "Unit 9.1 Learning Objectives Data Access in Code"— Presentation transcript:

1 Unit 9.1 Learning Objectives Data Access in Code
Data Access in Design (Review) Five Step Sequence Hands-on

2 the ConnectionString (e.g. csFees)
sqlDataSource (GUI) the SQL command the ConnectionString (e.g. csFees)

3 GUI Views DetailsView FormView GridView DataList ListView
Number of records One Many Insert Yes No Edit/Update Delete Column Format

4 Accessing Data Database server SQL e.g. MS SQL Server
SqlDataSource Database location (Connectionstring) What data (Command) What technology (Namespaces) Run! (DataReader) Browser e.g. FireFox Web server e.g. Windows Server Database server e.g. MS SQL Server HTML ASPX SQL ["1",“Registration Fee",5.00,”2”, “Vehicle License Fee",7.5,”3”, “Weight Fee“, ] Parse (Loop in Reader)

5 Five Steps to Data in code
The Five Step Plan Setup the page for the necessary technology Use Namespaces Setup the location to the database Create a Connection String Create a Command Object (SQL) The work required from the database Open the connection, Execute the Command, Create a Reader Execute! Loop through the Reader and read the data csFees myCommand GUI controls allow us to do a great deal but they can’t do everything .NET provides a number of objects that allow us to perform database manipulation in code The database objects are collected into three Namespaces A namespace is a way to uniquely identify a set of programming objects "1",“Registration Fee",5.00, ”2”, “Vehicle License Fee",7.50, ”3”, “Weight Fee“, 12.50

6 A. Get ready with Namespaces
Namespaces are libraries of database functions Needed while working with database in code “Using” suggests that these functions be loaded The following must be added at the top of the .cs file

7 B.1 Connection – What is it?
Called a Connection String (e.g. csFees) Stored in the web.config file Includes path and name to the database Is created automatically when an sds is configured

8 B.2 Connection – create in 3 steps
Using its name from the web.config file And can be pulled into your code with the ConfigurationManager Create a connection string object in your “.cs” page Finally, create the Connection Object These two should match Also used with sds In Design View

9 C.1 Command Object – What is it?
Equivalent to the GUI SQL Data Source Contains SQL, database driver, path, and name SQL commands: SELECT, INSERT, UPDATE, DELETE Two types: SELECT commands make DataReaders, and return data All other commends modify the data So they use ExecuteNonQuery & return a number

10 C.2 Command object – creating it
Tells the database what to do Is created with an SQL string & the connection object The Connection Object was made in the previous slide

11 D. Executing the Command - sequence
Open the connection Execute the command, create the reader Loop through the Reader AFTER the looping code, Close the connection // See next slide for looping code "1",“Registration Fee",5.00, ”2”, “Vehicle License Fee",7.50, ”3”, “Weight Fee“, 12.50

12 E. Parsing through the Reader
Review the SELECT statement Retrieve the records if there are any “.Read()” returns TRUE if there is a record FALSE if no records are found Address columns by index or field name Data type is always string There are several ways to process the RecordSet but the simplest is probably to use a DataReader Returns one record at a time to the program when the .Read() method is called Read() returns a value of false if there are no (more) records to read, true if there was a record Can be used to control a loop “Registration Fee",5.00, “Vehicle License Fee",7.50, “Weight Fee“, 12.50 lblFees.Text += "<br />" + strDescription + " " + decFee.ToString("c2");

13 F. Closing the Connection
Technically known as Garbage Collection Done to free up database server memory Critical step, causes Denial of Service on server myReader.Close(); myConnection.Close();

14 Parameters, a safety measure
Are a security measure Are placeholders of a values within SQL Values need to supplied before execution Adding a parameter to a command. The first argument is the name of the parameter, the second argument is the datatype (when you type System.Data.SqlDbType. you will see a list of all the SQL datatypes and can pick the appropriate one. 2. Parameter is given a value 3. Matches the SQL data type in the database 1. Parameter appears

15 L1: Hands on Purpose: To read and display all the records in a database then read and display selected records Start a new page yourlastnameU9L1 in the Unit9 folder. Add heading, heading size Reading Fee Data Using Code Add a Button to the page Button ID, button text Add a Label to hold the results displayed Label ID, text

16 U9L1 - 2 Write code that needs to be executed for the button. Use the five step plan: Import namespaces (Step A) Create the connection (Steps B.2.2 & B.2.3) Create an SqlCommand object (Step C) Execute the command object (Step D)

17 U9L1 - 3 Read the data record in a loop (Step E)
Copy the Description data from field 0 to a string variable Convert the Fee data from field 1 and store it in a decimal variable Accumulate the descriptions and fees in lblFees (without deleting previous entries) After the loop finishes, Close the Reader and the Connection (Step F) Add a try/catch block to the page Inside the try, put the risky code Inside the catch, display an appropriate error message

18 U9L1 - 4 Test your page, you should show fee descriptions and fee amounts, as shown on the right. Once that part works correctly skip a line after your label and type the words “Enter a test value:”, followed by a TextBox Set the (ID) of the TextBox to txtTest Validate for a positive decimal value

19 U9L1 - 5 Add a button on the line below the TextBox
Set the (ID) to btnTest2 Set the Text to “Display fees greater than or equal to the test value” Double click the button to start creating the method Copy all the code from the btnReadFees_Click method and paste it in the new method Locate the SQL statement and change it to say SELECT [FeeDescription], [Fee] FROM Fees WHERE [Fee]

20 U9L1 - 6 Add a new line of code after the line where you create the sqlCommand Get the test value from the TextBox And create a parameter with it (See slide on adding Parameters) decimal decTest = Convert.ToDecimal(txtTest.Text); System.Data.SqlDbType.Money).Value = decTest;

21 U9L1 - 7 Test your page and check the results. You should get something like this (depending on what data you have in your database) Add the assignment to your profile page, copy everything to ASPNET and post a link to your profile page in the dropbox


Download ppt "Unit 9.1 Learning Objectives Data Access in Code"

Similar presentations


Ads by Google