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

Slides:



Advertisements
Similar presentations
VB.NET Database Access ISYS546. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
Advertisements

Concurrency Control. R/RR/W W/W User 2 ReadWrite User 1 Read Write R/W: Inconsistent Read problem. W/W: Lost Update problem.
Authenticating Users in an ASP.NET Application. Web Site Administration Tool From VS 2008, click Website/ ASP.Net Configuration to open Web Site Administration.
Introduction to ADO.NET Programming. ADO.NET Objects Data Set.NET Applications Data Reader Command Object Connection Object Managed Data Provider (OLEDB)
ASP.NET and ADO.NET. ASP.NET Server Controls Intrinsic Controls: These controls correspond to their HTML counterparts. –Ex. Textbox, listbox, button,
VB.NET Database Tools ISYS Net Applications OLE DB Provider OLE DB Data Source OLE DB Provider ODBC Data Source SQL Server Data Source SQL Server.Net.
Coding ADO.NET Objects: Connection, Command, DataReader.
Website Security ISYS 512. Authentication Authentication is the process that determines the identity of a user. Web.config file – node Options: –Windows.
ASP.Net AJAX. AJAX Asynchronous JavaScript and XML: – JavaScript, Document Object Model, Cascade Style Sheet, XML, server-side script such as.Net, etc.
Introduction to Data Adapter. A Simplified View of ADO.Net Objects Ado.Net Data Provider Connection Adapter Command Reader Dataset Data Consumer WinForm.
ASP.NET and ADO.NET. ADO.NET Objects Data Set.NET Applications Data Reader Command Object Connection Object Managed Data Provider (OLEDB) Database.
Introduction to ADO.NET. ADO.NET Objects Data Set.NET Applications Data Reader Command Object Connection Object Managed Data Provider (OLEDB) Database.
Coding ADO.Net DataSet Objects. DataSet Object A DataSet object can hold several tables and relationships between tables. A DataSet is a set of disconnedted.
Web Site Security ISYS 512/812. Authentication Authentication is the process that determines the identity of a user. Web.config file – node Options: –Windows:
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS 512.
Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and.
Concurrency Control. R/RR/W W/W User 2 ReadWrite User 1 Read Write R/W: Inconsistent Read problem. W/W: Lost Update problem.
VB.NET Database Access ISYS 812. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
Coding ADO.Net DataSet Objects. DataSet Object A DataSet object can hold several tables and relationships between tables. A DataSet is a set of disconnedted.
VB.NET Database Tools ISYS 573. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
Introduction to Web Application Development with.Net and Web Service ISYS 350.
ASP.NET and ADO.NET. Bind the DataReader to a DataGrid Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = c:\sales2k.mdb" Dim objConn.
Introduction to ADO.NET. ADO.NET Objects Data Set.NET Applications Data Reader Command Object Connection Object Managed Data Provider (OLEDB) Database.
Coding ADO.NET Objects: Connection, Command, DataReader.
Introduction to ADO.Net and Visual Studio Database Tools ISYS 512.
VB.NET Classes ISYS 812. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)
Working with Session. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and lose their values.
VB.NET Database Access ISYS546. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS 512.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
VB.NET Classes ISYS 546. Classes A class is program structure that defines a user-defined data type that are used to create objects. An instance of a.
Website Security ISYS 512. Cookies Data in Cookies System.Web Which web site set the cookie Expiration date –DateTime data type –TimeSpan data type One.
Introduction to Web Service ISYS 512. Web Service XML Web Service Web services are classes that are stored on the web which can instantiate and use in.
Introduction to ADO.NET. ADO.NET Objects Data Set.NET Applications Data Reader Command Object Connection Object Managed Data Provider (OLEDB) Database.
ASP and HTML. Anchor Tag testAnchorTag Demo: ASPNet/ASPNETProdListSelf.ASPX.
Introduction to Structured Query Language SQL. SQL Select Command SELECT * FROM tableName WHERE criteria;
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS546.
Introduction to ADO.Net, VB.Net Database Tools and Data Binding ISYS 512.
Introduction to ADO.Net and Visual Studio Database Tools
VB.NET Database Access ISYS546. Microsoft Universal Data Access ODBC: Open Database Connectivity –A driver manager –Used for relational databases OLE.
Introduction to ADO.Net and Visual Studio Database Tools ISYS 512.
Needs for Accessing Database To make your web site more dynamic and maintainable, you can display information on your web pages that are retrieved from.
Introduction to XML and Web Service ISYS 464. HTML vs XML HTML is a language specifically designed for displaying information in browser. It doesn’t carry.
Website Security ISYS 512. Authentication Authentication is the process that determines the identity of a user.
ASP.Net and HTML. Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load dim strConn as string ="Provider=Microsoft.Jet.OLEDB.4.0;Data.
Module 3: Performing Connected Database Operations.
ADO.NET Objects – Data Providers Dr. Ron Eaglin. Requirements Visual Studio 2005 Microsoft SQL Server 2000 or 2005 –Adventure Works Database Installed.
Command Object’s ExecuteNonQuery Method ISYS 512.
JDS – VB.NET Skill Session Fall 2004 Presented by YUHAO LIN.
Introduction to ADO.Net and VS Database Tools and Data Binding ISYS 350.
Introduction to Query Language and SQL. Basic Query Language Operators Selection Projection Join Aggregates –Sum, Count, Max, Min, Avg SubTotal Calculated.
HNDIT Rapid Application Development
Created by Alia Al-Abdulkarim 2008 Visual Basic Vs. Java.
Coding ADO.NET Objects: Connection, Command, DataReader.
Using ADO.Net to Build a Login System Dr. Ron Eaglin.
ADO.NET Objects Data Adapters Dr. Ron Eaglin. Agenda Builds on Information in Part I Should have working knowledge of creating a database connection Continuation.
C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. –It describes a particular type of object. –It specifies the properties.
C# Classes ISYS 512. Introduction to Classes A class is the blueprint for an object. –It describes a particular type of object. –It specifies the properties.
Coding ADO.NET Objects: Connection, Command, DataReader.
ASP.NET Programming with C# and SQL Server First Edition
Coding ADO.NET Objects: Connection, Command, DataReader
ADO.NET Framework.
ASP.NET and ADO.NET.
Coding ADO.NET Objects: Connection, Command, DataReader
Database Handling Class and Service
ASP.NET and ADO.NET.
VB Classes ISYS 512.
Introduction to ADO.NET
Command Object’s ExecuteNonQuery Method
Introduction to ADO.Net and Visual Studio Database Tools.
Presentation transcript:

Coding ADO.NET Objects: Connection, Command, DataReader

A Simplified View of ADO.Net Objects Ado.Net Data Provider Connection Adapter Command Reader Dataset Data Consumer WinForm WebForm SQL Updates Results of SQL Selects

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.

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"

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 –BeginTransaction

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.

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.

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.

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

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.

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 Note1: Listbox is not bound. 2. SelectedItem

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

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") End Sub

Using a Parallel ArrayList to Store Cname and Rating ArrayList –Add –Clear –Remove –Item –IndexOf

Using a Parallel ArrayList Dim CnameList, RatingList As New ArrayList Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 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) objConn.Open() Dim objDataReader As OleDbDataReader objDataReader = objComm.ExecuteReader() Do While objDataReader.Read() = True ListBox1.Items.Add(objDataReader("cid")) CnameList.Add(objDataReader("cname")) RatingList.Add(objDataReader("Rating")) Loop End Sub

Use Listbox SelectedIndex Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged TextBox1.Text = CnameList(ListBox1.SelectedIndex) TextBox2.Text = RatingList(ListBox1.SelectedIndex) End Sub

Use SQL to Retrieve Summaries 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 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

Using Command’s ExecuteScalar to Run SQL Aggregates 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 count(cid) from customer';" Dim objComm As New OledbCommand(strSQL, objConn) objConn.Open() TextBox1.Text = objComm.ExecuteScalar

ExecuteScalar 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:\Company.accdb" Dim objConn As New OleDbConnection(strConn) Dim strSQL As String Select Case ListBox1.SelectedIndex Case 0 strSQL = "select count(eid) from emp';" Case 1 strSQL = "select Max(Salary) from emp';" Case 2 strSQL = "select Min(Salary) from emp';" End Select Dim objComm As New OledbCommand(strSQL, objConn) objConn.Open() TextBox1.Text = objComm.ExecuteScalar End Sub

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.

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

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

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

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.

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

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

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.

Declare OleDB objects and create listbox Imports System.Data.OleDb Public Class Form3 Inherits System.Windows.Forms.Form 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) 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

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

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

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=DCHAOD630\SQLExpress08;Initial Catalog=EmpDB;Integrated Security=True;Pooling=False" Dim objConn As New SqlConnection(strConn) Dim strSQL As String = "select * from emptable;" 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("eid")) Loop End Sub End Class