Download DataReader

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Concurrency control wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

SQL wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Database wikipedia , lookup

PL/SQL wikipedia , lookup

Functional Database Model wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Relational model wikipedia , lookup

Versant Object Database wikipedia , lookup

Clusterpoint wikipedia , lookup

Database model wikipedia , lookup

Transcript
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 and will DataSets in
Lecture Set 14C
DataReader



The DataReader is an component used for read-only
and forward-only connection to a database.
It is used to execute a query via a connection to a
database and iterate through the data returned by the
database.
The abstraction provided here is that of a connected
data architecture.
DataReader
Common properties and methods of the
SqlDataReader class
Property
IsClosed
Item(index)
Method
Close()
Read()
Description
Gets a value that indicates if the data reader is
closed.
Gets the value of the column with the specified
name or position.
Description
Closes the data reader.
Retrieves the next row and returns a Boolean value
that indicates whether there are additional rows.
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
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 (see Ch 11 Part C -- once it is done).

More on this in Part C.
DataReader Example
Dim strConnection As String = "provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=c:\path\Inventory.accdb;"
Dim
Dim
Dim
Dim
Dim
strSQL As String = "SELECT * FROM Product"
myConnection As New OleDbConnection(strConnection)
myCommand As New OleDbCommand(strSQL, myConnection)
myDataReader As OleDbDataReader
products As New SortedList(Of String, Double)
Try
myConnection.Open()
myDataReader = myCommand.ExecuteReader()
Do While myDataReader.Read()
Dim description As String = myDataReader("Description").ToString
Dim price As Double = CDbl(myDataReader("Price").ToString)
products.Add(description, price)
Loop
Catch ex As OleDbException
MessageBox.Show("Error: " & ex.Message)
Finally
myConnection.Close()
End Try
Example: Insert a Record
Dim strConnection As String = "provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=c:\path\School.accdb;"
Dim strSQL As String
strSQL = "INSERT INTO Students (StudentID, Lastname, Firstname, Major) " & _
"VALUES (‘" & txtSID.Text & "’,‘" & txtLN.Text & "’,‘" & txtFN.Text & _
"’,‘" & txtMajor.Text & "’)"
Dim myConnection As New OleDbConnection(strConnection)
Dim insertCommand As New OleDbCommand(strSQL, myConnection)
Try
myConnection.Open()
insertCommand.ExecuteNonQuery()
Catch ex As OleDbException
…
Catch ex As SystemException
…
Finally
myConnection.Close()
End Try
Example: Delete a Record
Dim strConnection As String = "provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=c:\path\School.accdb;"
Dim strSQL As String
strSQL = "DELETE FROM Students WHERE StudentID=‘" & txtSID.Text & "’"
Dim myConnection As New OleDbConnection(strConnection)
Dim deleteCommand As New OleDbCommand(strSQL, myConnection)
Try
myConnection.Open()
deleteCommand.ExecuteNonQuery()
Catch ex As OleDbException
…
Catch ex As SystemException
…
Finally
myConnection.Close()
End Try
Example: Update a Record
Dim strConnection As String = "provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=c:\path\School.accdb;"
Dim strSQL As String
strSQL = "UPDATE Students SET Major=‘" & txtMajor.Text & "’" & _
"WHERE StudentID=‘" & txtSID.Text & "’"
Dim myConnection As New OleDbConnection(strConnection)
Dim updateCommand As New OleDbCommand(strSQL, myConnection)
Try
myConnection.Open()
updateCommand.ExecuteNonQuery()
Catch ex As OleDbException
…
Catch ex As SystemException
…
Finally
myConnection.Close()
End Try
ADO.NET
DataReaders – main use

DataReaders


Simple and efficient way to retrieve results from
a query
Can use directly to process results of a select or
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
VB 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 VB .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 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.
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)

Direct insert of transaction into DB
‘Useful
Imports
Imports
Imports
imports
System.Data.OleDb
System.Convert
Microsoft.VisualBasic.ControlChars
...
' Write the Transaction to DB AND
' Get the MAX Transaction ID from DB to record transaction ID
Dim insertTransString As String = _
"INSERT INTO tblTransaction (fldTransactionDate, " _
"fldTransactionUser) VALUES (" & _
thisDate & ", " & frmMain.thisUserID.ToString & ")"
' Create insert and read commands to be transmitted to DB
Dim insertTransCommand As New OleDbCommand(insertTransString, OleConn)
Dim readTransCommand As New OleDbCommand("SELECT MAX(fldTransactionID) " _
"FROM tblTransaction", OleConn)
' Create DataReader object
Dim thisReader As OleDbDataReader
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 ex As Exception
MessageBox.Show(ex.ToString)
Finally
OleConn.Close()
End Try
...
Example 2 – Saving current record data
Try
' 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 VB code” as a collection of data of the same data
'
type -- the Object type.
' How do we know this? Look at thisReader.Item(0) and see what methods etc
'
are available. Then examine thisReader.GetInt32 and compare the two
If thisReader.Read() = True Then '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 VB .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
'MsgBox("No records")
. . .
End If
Catch ex As Exception
MsgBox("Read record error" & ex.ToString)
End Try
Example 3 – Using Max Transaction ID

Commit list of transactions to a DB
' Write the Line Items to DB
' Items already stored in productPriceList As New List(Of Product)
' getItem(i) gets field of ith item (product)in list
Dim insertLineString As String = ""
Dim insertLineCommand As New OleDbCommand(insertLineString, OleConn)
Try
OleConn.Open()
For i = 0 To count - 1
insertLineString = _
"INSERT INTO tblLineItem (fldLineItemTransactionID, " _
"fldLineItemName," & _
"fldLineItemPrice, fldLineItemCost) VALUES (" & _
thisTransactionID & ", " & Quote & getItem(i).productName & _
Quote & ", " & getItem(i).productPrice.ToString & ", " & _
getItem(i).productCost.ToString & ")"
' CommandText is a property of a Command object
insertLineCommand.CommandText = insertLineString
insertLineCommand.ExecuteNonQuery()
Next
Catch ex As Exception
MessageBox.Show(ex.ToString
Finally
OleConn.Close()
End Try
Example 4 – Delete
(remove)
a record
Private Sub btnDelete_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnDelete.Click
' Create a valid SQL delete string to remove
' current record from the database
Dim deleteString As String = _
"DELETE FROM tblEmployees " & CrLf & _
"WHERE tblEmployees.fldEmployeeID = " & (txtEmployeeID.Text)
MsgBox(deleteString)
' Create a new OleDbCommand object to delete the data
Dim deleteCommand As New _
System.Data.OleDb.OleDbCommand(deleteString, OleConn)
' Use a try-catch to delete the record
Try
deleteCommand.ExecuteNonQuery()
'Directly changes the DB
'MsgBox("Delete succeeded")
' Update result label
lblResult.Text = "Employee deleted"
Catch ex As Exception
MessageBox.Show("Delete record error " & ex.ToString)
End Try
' Reset the form
reset()
End Sub
Example 5 – Update a Record
Private Sub btnUpdate_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnUpdate.Click
' Create a valid SQL update string to change
' the data in the current record to match the
' data in the text boxes
Dim updateString As String = _
"UPDATE tblEmployees " & CrLf & _
"SET " & CrLf & _
"fldEmployeeType = " & Quote & txtEmployeeType.Text & Quote & ","
"fldEmployeeName = " & Quote & txtEmployeeName.Text & Quote & ","
"fldEmployeeAddress = " & Quote & txtEmployeeAddress.Text & Quote
"fldEmployeeSSN = " & Quote & txtEmployeeSSN.Text & Quote & "," &
"fldEmployeeSalary = " & txtEmployeeSalary.Text & " " & CrLf & _
"WHERE fldEmployeeID = " & txtEmployeeID.Text
MsgBox(updateString)
& CrLf & _
& CrLf & _
& "," & CrLf & _
CrLf & _
' Create a new OleDbCommand object to update the data
Dim updateCommand As New System.Data.OleDb.OleDbCommand(updateString, OleConn)
' Use a try-catch to update the record
Try
updateCommand.ExecuteNonQuery()
'Direct change in DB
'MsgBox("Update succeeded")
' Update result label
lblResult.Text = "Employee updated"
Catch ex As Exception
MessageBox.Show("Update record error " & ex.ToString)
End Try
End Sub
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 Employee-Manager code