lecture set 14 b new introduction to databases - database processing: the connected model (using...

26
Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Upload: allen-flowers

Post on 12-Jan-2016

218 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Lecture Set 14 B new

Introduction to Databases - Database Processing: The Connected Model (Using

DataReaders)

Page 2: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 2

Objectives

Understand database processing using ADO .NET

Perform specialized database processing tasks Work with database data programmatically

using either DataReaders (connected mode) DataSets (disconnected mode)

We discuss DataReaders here and will DataSets in Lecture Set 14C

Page 3: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 3

DataReader

The DataReader is a component used for read-only and forward-only connection to a database.

Results are returned as a query executes and stored in the network buffer on the client until you request them using the Read method of the DataReader. Using the DataReader can increase application performance both by retrieving data as soon as it is available, and (by default) storing only one row at a time in memory, reducing system overhead.

It is used to execute a query via a connection to a database and iterate through the data returned.

The abstraction provided here is that of a connected data architecture.

Page 4: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 4

DataReader

Common properties and methods of the SqlDataReader class

Property Description

IsClosed Gets a value that indicates if the data reader is closed.

Item(index) Gets the value of the column with the specified name or position.

Can also do this using form datareaderobject[“fieldname”];

Method Description

Close() Closes the data reader.

Read() Retrieves the next row and returns a Boolean value that indicates whether there are additional rows.

Page 5: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 5

Wizards and Bound Data vs DataReaders and DataSets

Wizard and data bound fields are useful for the rapid development of forms and displays based on content of a database

They are not useful for most transaction processing systems because of inflexibility

Use of code to control database access is more powerful because the programmer can manipulate data before it is stored or after it is retrieved

I prefer to avoid wizards where possible

Page 6: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 6

The Processing Sequence

Holds for both connected and disconnected architectures

Establish a connection to your data source using a Connection Object

These objects are simple to construct Create an SQL statement (a string) and wrap it in

a Command object These strings are harder to build – more detailed

Execute the Command object within the context of the Connected DB – there are methods for this

Process (retrieve or store) results of command if there are any

Use a DataReader object to scan through records [Use a combination of a DataAdapter and DataSet

(or DataTable) objects for storage and retrieval] Close all objects you opened to process data

Page 7: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 7

The Primary Objects

The Connection Object – Directs communication between your program and Data Source. Handles location and connection parameters for the data source.

The Command Object – Takes an SQL statement you provide (as a string) and prepares it for transport through the Connect-ion Object and subsequent processing in the specified DBMS.

The DataReader Object – Provides a simple and efficient way to retrieve results from an SQL query. It is used by other objects in ADO.NET to retrieve and redirect data within your program. You can use this reader directly to process the result of a SELECT or other retrieval action.

[The DataAdapter Object – Enables communication between a DataSet and the rest of the Provider. Modifies SELECT, DELETE, INSERT, and UPDATE statements for us by related data source (see Ch 11 Part C -- once it is done)].

Page 8: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 8

DataReader Example

string strConnection = "provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=c:\path\Inventory.accdb;";

string strSQL = "SELECT * FROM Product"; OleDbConnection myConnection = new OleDbConnection(strConnection); OleDbCommand myCommand = new OleDbCommand(strSQL, myConnection); OleDbDataReader myDataReader; SortedList<string, double> products = new SortedList<string, double>(4);

try { myConnection.Open(); myDataReader = myCommand.ExecuteReader();

while (myDataReader.Read()) { string description = myDataReader["Description"].ToString(); double price = Convert.ToDouble((myDataReader["Price"].ToString());

products.Add(description, price); } // end while } // end try

catch (OleDbException ex) { MessageBox.Show("Error: " + ex.Message); }

finally { myConnection.Close(); }

Page 9: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 9

Example: Insert a Record

string strConnection = "provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=c:\path\School.accdb;";

string strSQL; strSQL = "INSERT INTO Students (StudentID, Lastname, Firstname, Major) " + "VALUES (‘" + txtSID.Text + "’,‘" + txtLN.Text + "’,‘" + txtFN.Text +

"’,‘" + txtMajor.Text + "’)";

OleDbConnection myConnection = new OleDbConnection(strConnection); OleDbCommand insertCommand = new OleDbCommand(strSQL, myConnection);

try { myConnection.Open(); insertCommand.ExecuteNonQuery(); }

catch (OleDbException ex) … catch (SystemException ex) … finally { myConnection.Close(); }

Page 10: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 10

Example: Delete a Record

string strConnection = "provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=c:\path\School.accdb;" ;

string strSQL; strSQL = "DELETE FROM Students WHERE StudentID=‘" + txtSID.Text + "’" ;

OleDbConnection myConnection = new OleDbConnection(strConnection); OleDbCommand deleteCommand = new OleDbCommand(strSQL, myConnection);

try { myConnection.Open(); deleteCommand.ExecuteNonQuery(); }

catch (OleDbException ex) … catch (SystemException ex) … finally { myConnection.Close(); }

Page 11: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 11

Example: Update a Record

string strConnection = "provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=c:\path\School.accdb;" ;

string strSQL; strSQL = "UPDATE Students SET Major=‘" & txtMajor.Text + "’" + "WHERE StudentID=‘" & txtSID.Text & "’";

OleDbConnection myConnection = new OleDbConnection(strConnection) ; OleDbCommand updateCommand = new OleDbCommand(strSQL, myConnection) ;

try { myConnection.Open(); updateCommand.ExecuteNonQuery(); } catch (OleDbException ex) … catch (SystemException ex) … finally { myConnection.Close(); }

Page 12: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 12

ADO.NET

Page 13: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 13

DataReaders – main use

DataReaders Simple and efficient way to retrieve results

from a query Can use directly to process results of a

SELECT or to provide direct access INSERTs, DELETEs, and UPDATEs

A query gives you access to one row of table information at a time

Your connection must be open before a command is executed and should be closed when you are done

Page 14: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 14

Using DataReaders

} Database Result of Action Action (a table)

One or more rows

Use of dataReader object to make one row at a time of a database table “available” to your C# .NET code.

s, dbCon

Using DataReaders in Processing Database Records

Build an SQL string, s, for query, insert, delete, or update

Create a connection, dbCon, Between a database and a C# dataReader abstraction

Command

Page 15: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 15

The OleDbCommand Class

The OleDbCommand class stores SQL statements

The Connection property stores a reference to an OleDbConnection

The CommandText property stores an SQL statement

The CommandType should be set to Text

Page 16: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 16

DataSets vs DataReaders 1

DataReaders retrieve data in read only form. Data in a DataSet may be modified in memory and updated in one step

DataReaders allocate memory to one record (one table row) of data at a time. Efficient. Little overhead. DataSets are less efficient. Space must be allocated for entire table involved.

Only one record at a time can be processed. Random access through entire DataSet possible.

Only one DataReader can be open at a time. Multiple DataSets can be open at once.

Page 17: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 17

DataSets vs DataReaders 2

Live connection to the database exists as long as the DataReader is open. Data connections maintained only long enough to transfer data between DataSet and database.

With DataReaders you spend a lot of time working with strings (for SQL statements) and raw data fields (You supply all SQL statements). DataSets and DataAdapters assist in crafting SQL statements for you. All fields in a DataSet have the same logical organization as in the actual database.

Page 18: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 18

DataSets

Page 19: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 19

DataSets

Each DataSet contains one or more Tables Table[0], Table[1], Table[2] etc

Each DataTable contain one or more rows Row[0], Row[1], Row[2] etc

Each Row contains one or more fields These can be access by index [0]or by

field name [“StudentName”]

Page 20: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 20

Examples (Finally)

Illustrations of various DB commands Pattern of use of methods that are part of the

collection of class libraries that support “Providers” technology is complete consistent

Create a connection, dbCon, between your (client) code and the database

Build a database command (SQL select, update, insert, or delete) as a VB string s

Send the string and connection information via a command to the provider

Page 21: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 21

Example 1 – Insert (plus a simple select)(Uses Insert and DataReader commands to effect data transmission)

using System.Data.OleDb; using System.Convert; ... // Write the Transaction to DB AND // Get the MAX Transaction ID from DB to record transaction ID string insertTransString = "INSERT INTO tblTransaction (fldTransactionDate, " + "fldTransactionUser) VALUES (" + thisDate + ", " + frmMain.thisUserID.ToString() + ")"; // Create insert and read commands to be transmitted to DB OleDbCommand insertTransCommand = new OleDbCommand (insertTransString, OleConn); OleDbCommand readTransCommand = new OleDbCommand ("SELECT MAX(fldTransactionID) " + "FROM tblTransaction", OleConn); // Create DataReader object OleDbDataReader thisReader; try { OleConn.Open(); // OleConn is the Connection object insertTransCommand.ExecuteNonQuery(); // Insert one transaction // Next command executes SELECT to get Transaction Field ID thisReader = readTransCommand.ExecuteReader(); // Next - two methods needed on returned record from DataReader thisReader.Read(); thisTransactionID = thisReader.GetInt32[0]; // Gets first field read thisReader.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString); } finally { OleConn.Close(); } ...

Page 22: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 22

Example 2 – Saving a Current Recordtry { // The method thisReader.Read moves a pointer in the query table to // the next record. This causes the fields in that record to be // "presented to the C# code” as a collection of data of the same data // type -- the Object type. // How do we know this? Look at thisReader.Item and see what methods etc // are available. Then examine thisReader.GetInt32 and compare the two if (thisReader.Read() == true) // Implies valid data returned. False -> EOF txtEmployeeID.Text = thisReader.Item(0).ToString(); // The next line of code would also work // txtEmployeeID.Text = thisReader.GetInt32(0).ToString // This next example fails - specified cast is not valid. // Actual type NOT a string. Item(0) actually an integer. // Look up GetString method // txtEmployeeID.Text = thisReader.GetString(0) // All fields in DB are objects of some type such as Int32, String, Double // One "presented" to C# .NET environment, all the fields are of type Object // Next line won't compile. Object type can't be implicitly converted to string // txtEmployeeType.Text = thisReader.Item(1) txtEmployeeType.Text = thisReader.GetString(1); . . . txtEmployeeSalary.Text = thisReader.GetDouble(5).ToString(); btnNext.Enabled = true; lblResult.Text = "Results found"; lblInstructions.Text = "Please select an operation"' } else { MessageBox.Show("No records"); } . . . catch (Exception ex) { MsgBox("Read record error" + ex.ToString()); }

Page 23: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 23

Example 3 – Using Max Transaction ID

Commit list of transactions to a DB// Write the Line Items to DB // Items already stored in productPriceList = new List<Product> // getItem(i) gets field of ith item (product)in list string insertLineString = ""; OleDbCommand insertLineCommand = new OleDbCommand (insertLineString, OleConn); try { OleConn.Open(); for (i = 0; i < count; i++) { insertLineString = "INSERT INTO tblLineItem (fldLineItemTransactionID, " + "fldLineItemName," + "fldLineItemPrice, fldLineItemCost) VALUES (" + thisTransactionID + ", " + "\"" + getItem(i).productName + "\"" + ", " & getItem(i).productPrice.ToString + ", " + getItem(i).productCost.ToString + ")"; // CommandText is a property of a Command object insertLineCommand.CommandText = insertLineString; insertLineCommand.ExecuteNonQuery(); } // end for catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { OleConn.Close();}

Page 24: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 24

Example 4 – Delete (remove) a record

private void btnDelete_Click(object sender, EventArgs e) { // Create a valid SQL delete string to remove // current record from the database string deleteString = "DELETE FROM tblEmployees " + "\n" + "WHERE tblEmployees.fldEmployeeID = " + (txtEmployeeID.Text); MessageBox.Show(deleteString); // Create a new OleDbCommand object to delete the data System.Data.OleDb.OleDbCommand deleteCommand = new System.Data.OleDb.OleDbCommand(deleteString, OleConn); // Use a try-catch to delete the record try { deleteCommand.ExecuteNonQuery(); // Directly changes the DB // Update result label lblResult.Text = "Employee deleted"; catch (Exception ex) { MessageBox.Show("Delete record error " + ex.ToString()); } // Reset the form reset(); } // end btnDelete_Click

Page 25: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 25

Example 5 – Update a Record

private void btnUpdate_Click(object sender, EventArgs e) { // Create a valid SQL update string to change // the data in the current record to match the // data in the text boxes string updateString = "UPDATE tblEmployees " + "\n" + "SET " + "\n" + "fldEmployeeType = " + "\"" + txtEmployeeType.Text & "\"" + "," + "\n" + "fldEmployeeName = " + "\"" + txtEmployeeName.Text & "\"" + "," + "\n" + "fldEmployeeAddress = " + "\"" + txtEmployeeAddress.Text + "\"" + "," + "\n" + "fldEmployeeSSN = " + "\"" + txtEmployeeSSN.Text + "\"" + "," + "\n" + "fldEmployeeSalary = " + txtEmployeeSalary.Text + " " + "\n" + "WHERE fldEmployeeID = " + txtEmployeeID.Text; MessageBox.Show(updateString); // Create a new OleDbCommand object to update the data System.Data.OleDb.OleDbCommand updateCommand = new System.Data.OleDb.OleDbCommand(updateString, OleConn); // Use a try-catch to update the record try { updateCommand.ExecuteNonQuery(); //Direct change in DB // Update result label lblResult.Text = "Employee updated"; } catch (Exception e) { MessageBox.Show("Update record error " + ex.ToString); } // end btnUpdate_Click

Page 26: Lecture Set 14 B new Introduction to Databases - Database Processing: The Connected Model (Using DataReaders)

Slide 26

The Plan of Action

The goal is to have you work on Phase 2 of your lab using DataReaders

Then – as time permits, we will migrate over to the ASP.NET (client-server world) using Datasets

REMEMBER with DataReaders (in connected mode) all commands are executed on the database itself – not on any internal representation of the database.

To better understand the connected mode, study Your HW #10 VB Employee-Manager code as examined in

class Pascucci’s Small DB Example