Presentation is loading. Please wait.

Presentation is loading. Please wait.

Coding ADO.NET Objects: Connection, Command, DataReader

Similar presentations


Presentation on theme: "Coding ADO.NET Objects: Connection, Command, DataReader"— Presentation transcript:

1 Coding ADO.NET Objects: Connection, Command, DataReader

2 A Simplified View of ADO.Net Objects
Data Provider Data Consumer Adapter Dataset WinForm Connection Command WebForm Reader

3 Connection with a Connection Object
A connection object represents a unique session with a data source. Property: Connection string: string used to open a database. Data source, OLE DB provider, password, if any, security, etc. Methods: Use the Open/Close method to open/close a connection.

4 Connection String Containing information about database, OLE DB provider, password, if any, security, etc. For Jet database: ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb"

5 Providers Microsoft.Jet.OLEDB.4.0 MSDAORA – For Oracle MSDASQL
Microsoft OLE DB Provider for ODBC SQLOLEDB – Microsoft SQL Server

6 Connection Object Basic Methods: Open, Close BeginTransaction
Example 1: dim strConn as string ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" dim objConn as new OledbConnection(strConn) objConn.open() Example 2: dim objConn as new OledbConnection() objConn.ConnectionString=strConn Object Browser: System.Data.OleDB/oledbConnection/New Basic Methods: Open, Close BeginTransaction

7 Command Object The command object allows us to execute a SQL statement. Properties: CommandType: Text, stored procedure, tableDirect CommandText: SQL statement, procedure name, table name Connection Other properties: Parameters Basic Methods: ExecuteReader: Creates a DataReader object that contains the results of the query. ExecuteScalar: Executes the query, and returns the first column of the first row in the result set returned by the query. Typically used to execute a SQL aggregate function such as SUM, MAX, MIN, etc. ExecuteNonQuery: Change the data in a database without using a DataSet by executing SQL’s UPDATE, INSERT, or DELETE statements.

8 DataReader Object It is read-only and forward-only cursor.
Basic Methods: Read: Reads the current record and advances the pointer to the next record. It returns False if no more record in the DataReader. Close: Closes the dataReader. Property: HasRows – Boolean, indicates whether this System.Data.Common.DbDataReader contains one or more rows.

9 ExecuteReader Example
dim strConn as string ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" dim objConn as new OledbConnection(strConn) dim strSQL as string = "select * from customer;" dim objComm as new OledbCommand(strSQL,objConn) dim Results as string objConn.open() dim objDataReader as oledbDataReader objDataReader=objComm.executeReader() Note: No NEW in the Dim statement when define a dataReader object.

10 Import NameSpace The Imports statement must appear before all other declarations in a file and cannot appear inside a class or module declaration. Imports System.Data.OleDb Public Class Form1 Note: To import a nameSpace for all forms/modules in a project: Use Project Property Page: Imports

11 Read Records in a DataReader
dim Results as string do while objDataReader.Read()=true Results+=objDataReader("cid") + “ “ + objDataReader("Cname") + vbCrLF loop Textbox1.text=Results Note: objDataReader.Item(0) Note: objDataReader.Item(“cid”) Note: The Read method will (1) read a record, (2) advance pointer, (3) return true/false to indicate if more records exisit.

12 Add Items from a DataReader to a Listbox
Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select cname from customer;" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() Do While objDataReader.Read() = True LISTBOX1.Items.Add(objDataReader("cname")) Loop Note1: Listbox is not bound. 2. SelectedItem

13 Use SQL to Retrieve Summaries
Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select count(cid) as custCount from customer;" Dim objComm As New OleDbCommand(strSQL, objConn) Dim Results As String objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() If objDataReader.Read = True Then MessageBox.Show(objDataReader("custCount").ToString) End If Note: Alias select count(cid) as custCount

14 Using Command’s ExecuteScalar to Run SQL Aggregates
Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OledbConnection(strConn) Dim strSQL As String = "select count(cid) from customer';" Dim objComm As New OledbCommand(strSQL, objConn) objConn.Open() TextBox1.Text = objComm.ExecuteScalar

15 Testing for Null IsDBNull Function
If objDataReader.Read = True Then If IsDBNull(objDataReader("custCount")) Then TextBox1.Text = 0 Else TextBox1.Text = objDataReader("custCount").ToString End If Note: The keyword “Nothing” tests if an object is null.

16 Null Value Example Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select * from customer where cid = '" & ListBox1.SelectedItem & "'" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() objDataReader.Read() TextBox1.Text = objDataReader("Cname") TextBox2.Text = objDataReader("rating") ‘ Statement won’t work if Rating is null in database End Sub

17 Setting a Field to Null with a Update Statement
Dim strSQLUpd As String = "Update Customer Set Rating = null Where cid = '" & ListBox1.SelectedItem & "'"

18 Error Handling Try objConn.Open() Dim objDataReader As OleDbDataReader
objDataReader = objComm.ExecuteReader() Do While objDataReader.Read() = True Results += objDataReader("cid") + " " + objDataReader("Cname") + vbCrLf Loop TextBox1.Text = Results objConn.Close() Catch except As System.Exception MessageBox.Show(except.Message) End Try

19 Possible Database Errors
SQL syntax errors Database connection not open Null Violate database constraints Referential integrity Field data type and length Primary key constraint Invalid data – database may have validation rules.

20 ExecuteNonQuery Example
dim strSQLUpd as string="Update customer set rating = ‘A’” strSQLUpd=strSQLUpd & " where cname='" & CnameList.selectedItem.text & "'“ Dim objCommUpd As New OleDbCommand(strSQLUpd, objConn) objCommUpd.ExecuteNonQuery() Note: How many records affected by this command? ExecuteNonQuery method returns an integer indicating the number of record affected by the update command. Messagebox.Show(objCommUpd.ExecuteNonQuery())

21 Demo Create a project that do the following tasks:
Use a DataReader to retrieve customer IDs and populate a listbox. Select a new rating from radio buttons for the selected customer. Update customer’s rating using the ExecuteNonQuery method of a Command object. , fa n

22 Declare OleDB objects and create listbox
Imports System.Data.OleDb Public Class Form3 Inherits System.Windows.Forms.Form Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select cid from customer;" Dim objComm As New OleDbCommand(strSQL, objConn) Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() Do While objDataReader.Read() = True ListBox1.Items.Add(objDataReader("cid")) Loop objConn.Close() End Sub

23 Update customer rating
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click objConn.Open() Dim newRating As String If RadioButton1.Checked = True Then newRating = "A" ElseIf RadioButton2.Checked Then newRating = "B" Else newRating = "C" End If Dim strSQLUpd As String = "Update customer set rating = '" & newRating & "'" strSQLUpd = strSQLUpd & " where cid='" & ListBox1.SelectedItem & "'" Dim objCommUpd As New OleDbCommand(strSQLUpd, objConn) objCommUpd.ExecuteNonQuery() objConn.Close() End Sub

24 Use Command Object’s ExecuteNonQuery to Insert A New Record
Create unbound text boxes to enter new record. Add an Insert button with the following handler Dim strSQLInsert As String strSQLInsert = "Insert into Customer values ('" strSQLInsert = strSQLInsert & TextBox1.Text & "','" & TextBox2.Text & "','" strSQLInsert = strSQLInsert & TextBox3.Text & "','" & TextBox4.Text & "')" Dim objCommInsert As New OleDbCommand(strSQLInsert, objConn) objCommInsert.ExecuteNonQuery()

25 Database Processing with Classes

26 Single-Record-Handling Classes
Retrieves a single record from the database and makes it available to your application in the form of an object. The fields in the record are exposed as the object’s properties. Any actions performed by the data (updates, calculations, etc.) are exposed as the object’s methods.

27 Single-Record-Handling Class Example
Imports System.Data.OleDb Public Class Customer Public cid As String Public CName As String Public City As String Public Rating As String Private hiddenexist As Boolean Private cn As OleDb.OleDbConnection Public ReadOnly Property RecExist() Get RecExist = hiddenexist End Get End Property

28 Dim objConn As New OleDbConnection(strConn)
Public Sub getData(ByVal SearchID As String) Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select * from customer where cid = '" & SearchID & "'" Dim objComm As New OleDbCommand(strSQL, objConn) objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() If objDataReader.Read() = False Then hiddenexist = False MessageBox.Show("Record does not exist") Else hiddenexist = True cid = objDataReader("cid") CName = objDataReader("CName") City = objDataReader("City") Rating = objDataReader("Rating") End If objConn.Close() End Sub

29 Public Sub SaveNew() Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" Dim objConn As New OleDbConnection(strConn) objConn.Open() Dim strSQLInsert As String strSQLInsert = "Insert into Customer values ('" strSQLInsert = strSQLInsert & cid & "','" & CName & "','" strSQLInsert = strSQLInsert & City & "','" & Rating & "')" Dim objCommInsert As New OleDbCommand(strSQLInsert, objConn) objCommInsert.ExecuteNonQuery() objConn.Close() End Sub

30 Using the SaveNew Method to Add A New Customer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim newCust As New Customer() newCust.cid = TextBox1.Text newCust.CName = TextBox2.Text newCust.City = TextBox3.Text newCust.Rating = TextBox4.Text newCust.SaveNew() TextBox1.Text = "" TextBox2.Text = "" TextBox3.Text = "" TextBox4.Text = "" End Sub


Download ppt "Coding ADO.NET Objects: Connection, Command, DataReader"

Similar presentations


Ads by Google