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 Ado.Net Data Provider Connection Adapter Command Reader Dataset Data Consumer WinForm WebForm

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“ For Access 2007: –= "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\SalesDB2007.accdb“ For SQL Server Express –"Data Source=DCHAO100L\sqlexpress;Initial Catalog=testSQL08;Integrated Security=True"

5 Connection Object 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 strConn as string ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\salesDB.mdb" –dim objConn as new OledbConnection() –objConn.ConnectionString=strConn –objConn.open() Object Browser: System.Data.OleDB/oledbConnection/New Basic Methods: –Open, Close

6 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. –ExecuteNonQuery: Change the data in a database without using a DataSet by executing SQL’s UPDATE, INSERT, or DELETE statements.

7 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.

8 ExecuteReader Example dim strConn as string= "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\SalesDB2007.accdb“ 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.

9 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

10 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.

11 Add Items from a DataReader to a Listbox Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\SalesDB2007.accdb“ Dim objConn As New OleDbConnection(strConn) Dim strSQL As String = "select cid 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("cid")) Loop

12 Display Selected Customer Info in Textbox Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged Dim strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\SalesDB2007.accdb" 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") objDataReader.Close() End Sub

13 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.

14 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.ACE.OLEDB.12.0;Data Source=C:\SalesDB2007.accdb" 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

15 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

16 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.

17 Use Command Object’s ExecuteNonQuery to Insert A New Record 1.Create unbound text boxes to enter new record. 2.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()

18 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())

19 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.

20 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

21 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

22 Working with ODBC Data Source Imports System.Data.Odbc Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim strConn As String = "DSN=MySalesDB" Dim objConn As New OdbcConnection(strConn) Dim strSQL As String = "select cname from customer;" Dim objComm As New OdbcCommand(strSQL, objConn) objConn.Open() Dim objDataReader As OdbcDataReader objDataReader = objComm.ExecuteReader() Do While objDataReader.Read() = True ListBox1.Items.Add(objDataReader("cname")) Loop End Sub End Class

23 Working with SQL Server Data Source Imports System.Data.SqlClient Public Class Form9 Private Sub Form9_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim strConn As String = "Data Source=DCHAO100L\sqlexpress;Initial Catalog=testSQL08;Integrated Security=True" Dim objConn As New SqlConnection(strConn) Dim strSQL As String = "select * from customer;" Dim objComm As New SqlCommand(strSQL, objConn) objConn.Open() Dim objDataReader As SqlDataReader objDataReader = objComm.ExecuteReader() Do While objDataReader.Read() = True ListBox1.Items.Add(objDataReader("cname")) Loop End Sub End Class


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

Similar presentations


Ads by Google