Вы находитесь на странице: 1из 28

ADO.

NET
Part 1
What is ADO.NET?
• ADO is ActiveX Data Objects
• Provides access to data sources like SQL Server,
Oracle etc.
• It includes .NET Framework data providers for
connecting to a database, executing commands, and
retrieving results.
• ADO.NET comes with 4 database client namespace
1. For SQL Server
2. For Oracle
3. ODBC data source
4. Any database exposed through OLE DB.
Connections
IDbConnection

System.Data.
DbConnection Common

System.Data.Oracle DbConnectionBase

OracleConnection Others…

SQLConnection
System.Data.SqlClient
Establishing connection
• To establish a connection there are three
components that we need to specify in the form
of connection string
• Server where the database resides
• database name/instance
• authentication details to connect to the
database
Creating database and table
• In the IDE, open the ViewServer
Explorer.
• Select the server and enter the
database name as ‘Employee’
• Add new table called ‘Employee’ with
EID and Name as shown below.

• Enter some data into the table. Right


click the table and select ‘show table
data’
Testing connection and Obtaining
Connection String
• Right click Data Connections and click on ‘Add
Connection’.

• Select server name and database


name and click on ‘Test Connection’
to verify that connection is
established.
Copy the connection string from the property box of the
database instance that you created when ever you need it.
Code to view data
• Create a form with a button or menu, a label called Result.
Attach the following code to the button or menu on click
event to retrieve and display data by setting the Result
text.
‘Declaring all variables
Dim conn As SqlClient.SqlConnection
Dim source As String ??? COMING UP IN THE
Dim cmd As SqlClient.SqlCommand NEXT SLIDES…
Dim s As String
Dim reader As SqlClient.SqlDataReader
Paste the connection string here
source = “paste connection string"
conn = New SqlClient.SqlConnection(source)
conn.Open()
cmd = New SqlClient.SqlCommand("SELECT * FROM
EMPLOYEE", conn)
s = ""
reader = cmd.ExecuteReader()
While (reader.Read())
s = s & reader(0) & "-" & reader(1) & vbCrLf
End While
For new line(like \n in c#)
ResultL.Text = s
ResultL.Visible = True
conn.Close() Must close every connection
after you are done
Commands
• Command is a text containing SQL statement that is to
be issued to the database.
• A command could also be a stored procedure or the
name of the table that will retrieve all the columns and
rows from the table (like select * from table).
• A command is created by specifying command string
object and the connection object.
• Example from the previous slide:
cmd = New SqlClient.SqlCommand("SELECT *
FROM EMPLOYEE", conn);
• Other Command class examples are OracleCommand,
OleDbCommand etc.
Executing commands
• ExecuteNonQuery()
• Executes but does not return any output
• ExecuteReader()
• Executes and returns IDataReader type of
object
• ExecuteScalar()
• Executes and returns a single value
• ExecuteXmlReader (only for SqlCommand)
• Executes and returns XmlReader object.
Example for ExecuteNonQuery()
• Assume that we have two TextBox controls one for Name
and the other for ID. We will insert data that is entered
into these TextBoxes.
Dim source As String
Dim conn As SqlClient.SqlConnection
Dim cmd As SqlClient.SqlCommand
Dim name As String
Dim row As Integer
Dim id As Integer
source = "<conn-string>“
conn = New SqlClient.SqlConnection(source)
conn.Open()
id = Convert.ToInt32(IDTxt.Text)
name = NameTxt.Text
cmd = New SqlClient.SqlCommand("INSERT INTO EMPLOYEE
VALUES (" + id + ",'" + name + "')", conn)

row = cmd.ExecuteNonQuery()

ResultL.Text = row.ToString()
conn.Close()
Example for ExecuteScalar()
Dim source As String
Dim conn As SqlClient.SqlConnection
Dim cmd As SqlClient.SqlCommand
Dim o As System.Object
source = "Data Source=DEEPA-PC\\VAIO_VEDB;Initial
Catalog=Employee;Integrated Security=True"
conn = New SqlClient.SqlConnection(source)
conn.Open()
cmd = New SqlClient.SqlCommand("SELECT COUNT(*) FROM
EMPLOYEE", conn)
o = cmd.ExecuteScalar()
ResultL.Text = "No of records" + o.ToString()
ResultL.Visible = True
conn.Close()
Creating and calling a stored
procedure
• Create new stored procedure.

• Add the following procedure


ALTER PROCEDURE dbo.InsertEmployee(@ename
NCHAR(50),@ID INTEGER OUTPUT )
AS
SET NOCOUNT OFF
SELECT @ID=MAX(EID)+1 FROM EMPLOYEE
INSERT INTO EMPLOYEE VALUES(@ID,@ename)
RETURN
• Test new stored procedure.
Calling procedure from the C#
application
source = “<conn-string>”
name = NameTxt.Text
conn = New SqlClient.SqlConnection(source)
conn.Open()
cmd = New
SqlClient.SqlCommand(“dbo.InsertEmployee“,conn)
cmd.CommandType = CommandType.StoredProcedure
SqlDbType values
cmd.Parameters.Add(new
SqlClient.SqlParameter("@ename",SqlDbType.NChar
,30, "Name")) source column parameterName
cmd.Parameters.Add(new length of the parameter
SqlParameter("@ID",SqlDbType.Int,0,ParameterD
irection.Output,false,0,0,"EID",DataRowVersio
n.Default,Convert.DBNull))
Explained after the example
Sets how command results are applied to System.Data.DataRow when used
by the update method of the System.Data.Common.DbDataAdapter

Output parameters are mapped to the


cmd.UpdatedRowSource= changed row in System.Data.DataSet
UpdateRowSource.OutputParameters
cmd.Parameters("@ename”).Value=name
cmd.ExecuteNonQuery()
Ids=Convert.ToInt32(cmd.Parameters("@ID“).Value
) Set the value
ResultL.Text = "new id"+ ids to the
parameter
ResultL.Visible = true Get the value into
conn.Close() the parameter

All these are ok….. But what is System.Data.DataRow,


System.Data.Common.DbDataAdapter etc.

System.Data namespace contains generic data access classes.


System.Data.Common : contain classes shared (or overridden)
by individual data providers.
SQLParameter
• parameterName : The name of the parameter to map.
• dbType :One of the SqlDbType values.
• size : The length of the parameter.
• direction: One of the ParameterDirection values.
• isNullable: true if the value of the field can be null,
otherwise false.
• precision: The total number of digits to the left and
right of the decimal point to which Value is resolved.
• scale: The total number of decimal places to which
Value is resolved.
• sourceColumn: The name of the source column.
• sourceVersion: One of the DataRowVersion values.
• value: An Object that is the value of the SqlParameter.
cmd.Parameters.Add(new
SqlParameter("@ID",SqlDbType.Int,0,ParameterDirection.O
utput,false,0,0,"EID",DataRowVersion.Default,””))
Converting data into XML
• The ExecuteXmlReader() method on
command object returns an XmlReader
object.
• This object returns the XML converted version
of the rows that are returned.
• This facility is provided only for Sql Server
implies for SqlClient Provider only.
• SQL server requires the SQL Select statement
to be extended with a FOR XML clause for this
to work.
FOR XML Clause
• FOR XML AUTO
• Builds a tree based on the tables in the FROM
clause
• FOR XML RAW
• Maps result set rows to elements, with
columns mapped to attributes
• FOR XML EXPLICIT
• Requires that you specify the shape of the
XML tree to be returned.
Example with FOR XML AUTO
‘Declare all variables used according to type
source = "<<conn-string>>"
conn = New SqlClient.SqlConnection(source)
conn.Open()
cmd = New SqlClient.SqlCommand("SELECT EID, NAME FROM
EMPLOYEE FOR XML AUTO", conn)
xml = cmd.ExecuteXmlReader()
xml.Read()
s = ""
Do
t = xml.ReadOuterXml()
s = s + t + vbCrLf
Loop While (Not String.IsNullOrEmpty(t))
ResultL.Text = s
conn.Close()
Transactions
• When there are multiple updates to the database and
these must be performed as a unit of single database
transaction, ADO.NET provides SqlTransaction class.
‘other declarations
Dim tx As SqlClient.SqlTransaction
source = “connection string“
conn = New SqlClient.SqlConnection(source)
conn.Open()
Try
tx = conn.BeginTransaction()
'do some updations
tx.Commit()
conn.Close()
Catch ex As Exception
tx.Rollback()
End Try
conn.Close()
Transaction Isolation Level
• Various Isoloation Level available in
VB.NET are
• Chaos
• ReadCommitted
• ReadUnCommitted
• RepeatableRead
• Serializable
• SnapShot
• Unspecified
Transaction Isolation Level
• Serailizable :
• This isolation level specifies that all
transactions occur in a completely isolated
fashion; i.e., as if all transactions in the
system had executed serially, one after the
other. The DBMS may execute two or more
transactions at the same time only if the
illusion of serial execution can be maintained.
At this isolation level, phantom reads cannot
occur. Most exclusive transaction level.
• RepeatableRead
• All data records retrieved by a SELECT statement
cannot be changed; however, if the SELECT
statement contains any ranged WHERE clauses,
phantom reads may occur. In this isolation level the
transaction acquires read locks on all retrieved
data, but does not acquire range locks.
• ReadCommitted
• Data records retrieved by a query are not
prevented from modification by some other
transaction. Non-repeatable reads may occur,
meaning data retrieved in a SELECT statement
may be modified by some other transaction when it
commits. In this isolation level, read locks are
acquired on selected data but they are released
immediately whereas write locks are released at
the end of the transaction.
•ReadUncommitted:
•In this isolation level, dirty reads are allowed.
One transaction may see uncommitted changes
made by some other transaction.
Setting isolation level
• You can set isolation level when invoking
BeginTransaction method.
• Example
Dim myTrans as
SqlClient.SqlTransaction
myTrans =
myConnection.BeginTransaction(Syst
em.Data.IsolationLevel.RepeatableR
ead)
• ReadCommitted is default for SQL Server

Вам также может понравиться