17
030010401 BCA 4th Semester Preeti P Bhatt Department of Computer Science, UTU. 1 | Page 030010401- GUI Programming Unit-4: ADO.NET Programming BCA 4 th Semester Note: - This material is prepared by Ms. Preeti P Bhatt. The basic objective of this material is to supplement teaching and discussion in the classroom. Student is required to go for extra reading in the subject through library work.

Unit4

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Unit4

030010401 BCA 4th Semester

Preeti P Bhatt Department of Computer Science, UTU. 1 | P a g e

030010401- GUI Programming

Unit-4: ADO.NET Programming

BCA 4th Semester

Note: - This material is prepared by Ms. Preeti P Bhatt. The basic

objective of this material is to supplement teaching and discussion

in the classroom. Student is required to go for extra reading in the

subject through library work.

Page 2: Unit4

030010401 BCA 4th Semester

Preeti P Bhatt Department of Computer Science, UTU. 2 | P a g e

Topic Covered

ADO.NET architecture and its component

Connected and disconnected architecture

Working with the DataSet: creating, filling and modifying DataSet, DataGrid control

Accessing data: Executing query using Command object, reading data using DataReader

Executing stored procedure

Page 3: Unit4

030010401 BCA 4th Semester

Preeti P Bhatt Department of Computer Science, UTU. 3 | P a g e

ADO.NET

ADO.NET is a data access technology from Microsoft .Net Framework , which provides communication between relational and non-relational systems through a common set of components. ADO.NET consists of a set of Objects that expose data access services to the .NET environment.

ADO.NET is built for disconnected architecture, so it enables truly disconnected Data Access and Data Manipulation through its Dataset Object, which is completely independent from the Data Source.

ADO.NET provides • Methods for connecting to data sources • Retrieving • Manipulating • Updating.

ADO.NET Architecture

Page 4: Unit4

030010401 BCA 4th Semester

Preeti P Bhatt Department of Computer Science, UTU. 4 | P a g e

Two Main Component of ADO.Net

1. Data Provider

The Data Provider is responsible for providing and maintaining the connection to the

database.

Data Provider is a set of ADO.NET classes that allows you to access specific database,

execute SQL command and retrieve the data.

A data provider is a bridge between your application and a data source.

Four Data Providers for ADO.NET

OLEDB Provider: (Object Linking and Embedding Database)

o Provides access to any data source that has OLEDB driver.(like Access )

o Namespace : OleDb

Members provide a direct connection to COM(Component Object

Model)-based OLE DB data providers for databases and data

sources other than SQL Server and Oracle.

ODBC Provider: (Open Database Connectivity)

o Provides access to any data source that has an ODBC driver.

o Namespace : ODBC

Members provide connectivity to legacy data sources that don’t

have OLE DB data providers.

SQLServer Provider: provides access to SQL server database

o Namespace : SqlClient

Members provide high performance connectivity to SQL Server.

Oracle Provider: provides access to Oracle database.

o Namespace : SqlClient

Members deliver functionality similar to SqlClient for Oracle

databases.

How to Import Namespace?

Sql Example

Imports System.Data ‘For dataset object

Imports System.Data.SQLClient ‘For data provider object

Page 5: Unit4

030010401 BCA 4th Semester

Preeti P Bhatt Department of Computer Science, UTU. 5 | P a g e

Object of data provider

The four Objects from the .Net Framework provide the functionality of Data Providers

in ADO.NET.

Connection Object

Command

Data Reader

Data Adapter

Connection

Connection class allows you to establish a connection to data source.

The connection string is a series of name/value setting separate by semicolon (;)

The few information required in connection string are

Server where database is located

Database you want to use

Database should authenticate you

Connections can be opened in two ways:

Explicitly by calling the Open method on the connection

Implicitly when using a DataAdapter.

When creating a connection object you can pass the connection string as a constructor

parameter.

You can also set the ConnectionString property by hand.

Ex: connection with SqlClient

Without argument constructor

Dim connection as new SqlConnection()

connection.ConnectionString= “Connection String"

With Argument constructor

Dim connection As SqlConnection

Connection = New SqlConnection ("Connection String")

Common properties and methods

Method/Property Use

Open() open the connection

Close() Close the connection()

ConnectionString The string use to make connection with database

Page 6: Unit4

030010401 BCA 4th Semester

Preeti P Bhatt Department of Computer Science, UTU. 6 | P a g e

Command

The command class allows you to execute any type of SQL Command.

You can also use command class to perform user defined task such as create table, alter table etc.

Example: Dim cnn As SqlConnection

Dim cmd As SqlCommand

cnn = New SqlConnection(“ConnectionString”)

cmd = New SqlCommand("Your SQL Statement Here", cnn)

Property of Command Object o Connection o CommandType o CommandText o Parameters

Methods for execute commands on the database:

● ExecuteNonQuery: Executes commands that have no return values such as INSERT, UPDATE or DELETE

● ExecuteScalar: Returns a single value from a database query.

● ExecuteReader: Returns a result set by way of a DataReader object.

Data Reader

DataReader Object in ADO.NET is a stream-based, forward-only, read-only retrieval of

query results from the Data Source, which do not update the data.

The DataReader cannot be created directly from code; they created only by calling the

ExecuteReader method of a Command Object.

Dim cmd As SqlCommand(“Query”, con)

Dim DataReader As new SqlDataReader

DataReader = Command.ExecuteReader()

Common methods of DataReader

o Read() : It is used to read the rows from DataReader and it always moves forward to a new valid row, if any row exist .

o Close() : it used to close dataReader connection with database.

Page 7: Unit4

030010401 BCA 4th Semester

Preeti P Bhatt Department of Computer Science, UTU. 7 | P a g e

Data Adapter

DataAdapter is a part of the ADO.NET Data Provider. DataAdapter provides the

communication between the Dataset and the Datasource.

We can use the DataAdapter in combination with the DataSet Object. That is these two

objects combine to enable both data access and data manipulation capabilities.

The DataAdapter can perform Select, Insert, Update and Delete SQL operations in the

Data Source.

The Insert, Update and Delete SQL operations, we are using the continuation of the

Select command perform by the DataAdapter.

That is the DataAdapter uses the Select statements to fill a DataSet and use the other

three SQL commands (Insert, Update, delete) to transmit changes back to the

Database.

Example: Using Command Object

Dim sqlCmd As SqlCommand

Dim adapter As SqlDataAdapter

Dim ds As New DataSet

sqlCmd = New SqlCommand(“Your Select Query”, sqlCnn)

adapter = New SqlDataAdapter(cmd)

adapter.Fill(ds)

Example: Without using Command Object

Dim adapter As SqlDataAdapter

Dim ds As New DataSet

adapter = New SqlDataAdapter(“Your Select Query”, sqlCnn)

adapter.Fill(ds)

Methods of DataAdapter

Fill()

FillSchema()

Update()

Page 8: Unit4

030010401 BCA 4th Semester

Preeti P Bhatt Department of Computer Science, UTU. 8 | P a g e

2. DataSet : Second component of ADO.Net

The DataSet is the heart of disconnected data access.

The ADO.NET DataSet contains DataTableCollection and their DataRelationCollection .

It represents a collection of data retrieved from the Data Source. We can use Dataset in

combination with DataAdapter class.

The DataSet object offers disconnected data source architecture. The Dataset can work

with the data it contains, without knowing the source of the data coming from. That is,

the Dataset can work with a disconnected mode from its Data Source.

It gives a better advantage over DataReader , because the DataReader is working only

with the connection oriented Data Sources.

Example

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles Button1.Click

Dim connetionString As String

Dim connection As SqlConnection

Dim command As SqlCommand

Dim adapter As New SqlDataAdapter

Dim ds As New DataSet

Dim i As Integer

Dim sql As String

connetionString = "Data Source=ServerName;Initial

Catalog=DatabaseName;User ID=UserName;Password=Password"

sql = "Your SQL Statement Here"

connection = New SqlConnection(connetionString)

Page 9: Unit4

030010401 BCA 4th Semester

Preeti P Bhatt Department of Computer Science, UTU. 9 | P a g e

Try

connection.Open()

command = New SqlCommand(sql, connection)

adapter.SelectCommand = command

adapter.Fill(ds)

adapter.Dispose()

command.Dispose()

connection.Close()

For i = 0 To ds.Tables(0).Rows.Count - 1

MsgBox(ds.Tables(0).Rows(i).Item(0) & " -- " &

ds.Tables(0).Rows(i).Item(1))

Next

Catch ex As Exception

MsgBox("Cannot open connection ! ")

End Try

End Sub

End Class

Connected and Disconnected Architecture

The ADO.NET Framework supports two models of Data Access Architecture,

Connection Oriented Data Access Architecture Disconnected Data Access Architecture.

Connection Oriented Data Access

In Connection Oriented Data Access Architecture the application makes a connection to the Data Source and then interacts with it through SQL requests using the same connection.

In these cases the application stays connected to the database system even when it is not using any Database Operations.

Connected Environment (Scenario) 1. Open connection

2. Execute command

3. Process rows in reader

4. Close reader

5. Close connection

Working with data directly via open connection

Advantages Drawbacks

Simple security realization

Work with real data

Simple organization of distributed work

Continual connection

Not available via Internet

Page 10: Unit4

030010401 BCA 4th Semester

Preeti P Bhatt Department of Computer Science, UTU. 10 | P a g e

Disconnection Oriented Data Access

ADO.Net solves connection problem by introduces a new component called Dataset.

The DataSet is the central component in the ADO.NET Disconnected Data Access Architecture. A DataSet is an in-memory data store that can hold multiple tables at the same time.

Datasets only hold data and do not interact with a Data Source.

Disconnected Environment (Scenario) 1. Open connection

2. Fill the DataSet

3. Close connection

4. Process the DataSet

5. Open connection

6. Update the data source

7. Close connection

Accessing data: Executing query using Command object, reading data

using DataReader

Executing query using Command object Insert Update Delete Select

Reading data using DataReader While select query is used

Example: Executing Query using command Object and DataSet

Page 11: Unit4

030010401 BCA 4th Semester

Preeti P Bhatt Department of Computer Science, UTU. 11 | P a g e

Imports System.Data.SqlClient

Public Class Form1

Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=

D:\DotNetProgramming 2013\VB.NetProgramDemo\SQLConnectivity\SQLConnectivity\

EMP.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")

Dim cmd As New SqlCommand()

Dim ad As New SqlDataAdapter()

Dim ds As New DataSet

Dim i As Integer

‘Code For Insert Query

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnSave.Click

Try

con.Open()

cmd = New SqlCommand("insert into emp_info values

(@id,@name,@desg,@salary)",con)

cmd.Parameters.AddWithValue("@id", Convert.ToInt32(txtId.Text))

cmd.Parameters.AddWithValue("@name", txtName.Text)

cmd.Parameters.AddWithValue("@desg", cbDsgn.SelectedItem)

cmd.Parameters.AddWithValue("@salary", Convert.ToInt32(txtSal.Text))

i = cmd.ExecuteNonQuery()

MsgBox("Data Inserted")

display()

Catch ex As Exception

MsgBox(ex.Message)

End Try

con.Close()

End Sub

‘Code For Delete Query

Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnDelete.Click

Try

con.Open()

cmd = New SqlCommand("delete from emp_info where id=@id", con)

cmd.Parameters.AddWithValue("@id", Convert.ToInt32(txtId.Text))

i = cmd.ExecuteNonQuery()

MsgBox("Data deleted")

display()

Catch ex As Exception

MsgBox(ex.Message)

End Try

con.Close()

End Sub

Page 12: Unit4

030010401 BCA 4th Semester

Preeti P Bhatt Department of Computer Science, UTU. 12 | P a g e

Public Sub display()

ds.Clear()

ad = New SqlDataAdapter("select * from emp_info ", con)

ad.Fill(ds, "Temp")

dataGrid.DataSource = ds

dataGrid.DataMember = "Temp"

End Sub

‘Code For Select Query

Private Sub btnSelect_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnSelect.Click

con.Open()

display()

con.Close()

End Sub

‘Code For Update Query

Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnUpdate.Click

Try

con.Open()

cmd = New SqlCommand("update emp_info set name=@name, designation=@desg,

salary=@salary where id=@id", con)

cmd.Parameters.AddWithValue("@id", Convert.ToInt32(txtId.Text))

cmd.Parameters.AddWithValue("@name", txtName.Text)

cmd.Parameters.AddWithValue("@desg", cbDsgn.SelectedItem)

cmd.Parameters.AddWithValue("@salary", Convert.ToInt32(txtSal.Text))

i = cmd.ExecuteNonQuery()

MsgBox("Data Updated")

display()

Catch ex As Exception

MsgBox(ex.Message)

End Try

con.Close()

End Sub

‘Code For cell selection in gridview

Private Sub dataGrid_CellClick(ByVal sender As System.Object, ByVal e As

System.Windows.Forms.DataGridViewCellEventArgs) Handles dataGrid.CellClick

Dim r As Integer

r = dataGrid.CurrentCell.RowIndex

txtId.Text = dataGrid.Rows(r).Cells(0).Value

txtName.Text = dataGrid.Rows(r).Cells(1).Value

cbDsgn.SelectedItem = dataGrid.Rows(r).Cells(2).Value

txtSal.Text = dataGrid.Rows(r).Cells(3).Value

End Sub

Page 13: Unit4

030010401 BCA 4th Semester

Preeti P Bhatt Department of Computer Science, UTU. 13 | P a g e

‘Code For Select Query

Sub Navigate()

Dim r As Integer

r = Me.BindingContext(ds, "Temp").Position

txtId.Text = dataGrid.Rows(r).Cells(0).Value

txtName.Text = dataGrid.Rows(r).Cells(1).Value

cbDsgn.SelectedItem = dataGrid.Rows(r).Cells(2).Value

txtSal.Text = dataGrid.Rows(r).Cells(3).Value

End Sub

Private Sub btnCurrent_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnCurrent.Click

Navigate()

End Sub

Private Sub btnLast_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnLast.Click

Me.BindingContext(ds, "Temp").Position = Me.BindingContext(ds,

"Temp").Count - 1

Navigate()

End Sub

Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnNext.Click

Me.BindingContext(ds, "Temp").Position = Me.BindingContext(ds,

"Temp").Position + 1

Navigate()

End Sub

Private Sub btnPrevious_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnPrevious.Click

Me.BindingContext(ds, "Temp").Position = Me.BindingContext(ds,

"Temp").Position - 1

Navigate()

End Sub

Private Sub btnFirst_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btnFirst.Click

Me.BindingContext(ds, "Temp").Position = 0

Navigate()

End Sub

End Class

Page 14: Unit4

030010401 BCA 4th Semester

Preeti P Bhatt Department of Computer Science, UTU. 14 | P a g e

Example: Reading data using DataReader

DataGrid Control

The DataGridView can display data in

Bound mode – Static Binding- Directly from Gridview Bound mode is suitable for managing data using automatic interaction with the

data store. One very common use of the DataGridView control is binding to a table in a

database. Unbound mode – Dynamic Binding (Using Code)

Unbound mode is suitable for displaying relatively small amounts of data that you manage programmatically.

To bind GridView we can use two properties

DataSource— It gets or sets DataSource that the DataGridView is displaying data.

The data source, typically a dataset

DataMember— It get or set the name of the table in the DataSource for which the

DataGridView is display data.

Example: DataGridView1.DataSource = dataset Object

DataGridView1.DataMember = “Student"

Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=D:

\DotNetProgramming 2013\VB.NetProgram

Demo\SQLConnectivity\SQLConnectivity\EMP.mdf;

Integrated Security=True;Connect Timeout=30;User

Instance=True")

Dim cmd As New SqlCommand()

Dim dr As SqlDataReader

cmd = New SqlCommand("select * from emp_info ", con)

dr = cmd.ExecuteReader()

While dr.Read()

MsgBox(dr(0) & " , " & dr(1) & " , " & dr(2) & " , " & dr(3))

End While

dr.Close()

con.Close()

Page 15: Unit4

030010401 BCA 4th Semester

Preeti P Bhatt Department of Computer Science, UTU. 15 | P a g e

Working with the Dataset:

Dataset is a disconnected, in-memory representation of the data.

It can be consider as local copy of portion of database.

It can be manipulated and updated independent of the database.

Creating, filling and modifying DataSet

o Create object of dataset

o Create DataTable object

o Create DataColumn object

o Add Column in DataTable

o Create DataTable row

o Assign value in each column

o Add DataTable in DataSet

Example

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim idCoulumn As DataColumn

Dim nameCoulumn As DataColumn dt = New DataTable() dt.TableName = "Data" idCoulumn = New DataColumn("ID", Type.GetType("System.Int32")) nameCoulumn = New DataColumn("Name", Type.GetType("System.String"))

dt.Columns.Add(idCoulumn) dt.Columns.Add(nameCoulumn) dr = dt.NewRow() dr("ID") = 1 dr("Name") = "Name1" dt.Rows.Add(dr) dr = dt.NewRow() dr("ID") = 2 dr("Name") = "Name2" dt.Rows.Add(dr)

ds.Tables.Add(dt)

End Sub

Page 16: Unit4

030010401 BCA 4th Semester

Preeti P Bhatt Department of Computer Science, UTU. 16 | P a g e

Executing stored procedure

The data provider is a set of components that include the Connection, Command, DataReader, and DataAdapter Objects.

The command Object provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions.

A stored procedure is a precompiled executable object that contains one or more SQL statements. A sample Stored Procedure is given below:

CREATE PROCEDURE Procedure_name

AS

Procedure Command

GO

Example

CREATE PROCEDURE SPPUBLISHER

AS

SELECT PUB_NAME FROM publishers

GO

The above code creates a procedure named as 'SPPUBLISHER' and it execute SQL statement that selects all publisher names from publishers table from the PUB database.

Using stored procedures, database operations can be encapsulated in a single command, optimized for best performance, and enhanced with additional security.

To call a stored procedure from VB.NET application, set the CommandType of the Command object to StoredProcedure.

Command.CommandText=”StoreProcedure Name”

command.CommandType = CommandType.StoredProcedure

Page 17: Unit4

030010401 BCA 4th Semester

Preeti P Bhatt Department of Computer Science, UTU. 17 | P a g e

From the following source code you can see how to call a stored procedure from VB.NET application.

Imports System.Data.SqlClient

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles Button1.Click

Dim connetionString As String

Dim connection As SqlConnection

Dim adapter As SqlDataAdapter

Dim command As New SqlCommand

Dim ds As New DataSet

Dim i As Integer

connetionString = "Data Source=servername;Initial

Catalog=PUBS;User ID=sa;Password=yourpassword"

connection = New SqlConnection(connetionString)

connection.Open()

command.Connection = connection

command.CommandType = CommandType.StoredProcedure

command.CommandText = "SPPUBLISHER"

adapter = New SqlDataAdapter(command)

adapter.Fill(ds)

For i = 0 To ds.Tables(0).Rows.Count - 1

MsgBox(ds.Tables(0).Rows(i).Item(0))

Next

connection.Close()

End Sub

End Class