* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Lecture Set 14B new
Concurrency control wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Microsoft SQL Server wikipedia , lookup
Open Database Connectivity wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Functional Database Model wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Versant Object Database wikipedia , lookup
Relational model wikipedia , lookup
Lecture Set 14 B new Introduction to Databases Database Processing: The Connected Model (Using DataReaders) 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 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. DataReader Common properties and methods of the SqlDataReader class Property IsClosed Item(index) Description Gets a value that indicates if the data reader is closed. Gets the value of the column with the specified name or position. Can also do this using form datareaderobject[“fieldname”]; Method Close() Open() Read() Description Closes the data reader. Opens a data reader Retrieves the next row and returns a Boolean value that indicates whether there are additional rows. The Processing Sequence Holds for both connected and disconnected architectures Establish a connection to your data source using a Connection Object Create an SQL statement (a string) and wrap it in a Command object These objects are simple to construct 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 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 Connection 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 (not discussed in this slide set)]. 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(); } 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(); } 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(); } 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(); } 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 Using DataReaders 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 Database Action s, dbCon 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. Result of Action (a table) 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 property should be set to Text 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. 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. DataSets Each DataSet contains one or more Tables Each DataTable contain one or more rows Table[0], Table[1], Table[2] etc 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”] Data Sets vs Data Readers Remember – these are two different abstract models for accessing a database They each have their pros and cons We will use the DataReader model in CIS 3309 and the DataSet model in 3342 We are coordinated … well – to some extent 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 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(); } Example 2 – 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();} Example 3 – 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 Example 4 – 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 & "\"" + "," "fldEmployeeName = " + "\"" + txtEmployeeName.Text & "\"" + "," "fldEmployeeAddress = " + "\"" + txtEmployeeAddress.Text + "\"" "fldEmployeeSSN = " + "\"" + txtEmployeeSSN.Text + "\"" + "," + "fldEmployeeSalary = " + txtEmployeeSalary.Text + " " + "\n" + "WHERE fldEmployeeID = " + txtEmployeeID.Text; MessageBox.Show(updateString); + "\n" + + "\n" + + "," + "\n" "\n" + // 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 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) in which DataSets will be used (although we will not get that far in 3309) 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