Sei sulla pagina 1di 6

Data Access Technologies: to build efficient applications to manage data, regardless of source.

1. ADO.NET – for managed code – in VB C # C++ – .NET


2. MS ODBC – for native code – in C C++ – windows
3. (OLE) DB – – in VB6 (COM) C++(COM) – ASP
4. JDBC – for java code – – SQL server

 Standards laid down by W3C; Can retrieve from one data source (MS excel) and save in another (XML doc)
 ADO.NET object model: data provider – dataset - connection

Data Provider: for connecting to database, retrieving data, storing it in dataset, reading and retrieving it and
updating the database. Choice of provider depends on the data source being accessed.
1. SQL Server- System.Data.dll  System.Data.SqlCLient namespace
2. OLEDB - System.Data.dll  System.Data.OleDb namespace (through COM)
3. ODBC - System.Data.ODBC.dll  not a part of visual studio .net installation (through COM)
4. Oracle - System.Data.OracleClient.dll  System.Data.OracleClient namespace
*COM – Component Object Model – ActiveX

System.Data namespace  DataSet class


System.Data.SqlClient namespace  SqlConnection class

Dataset:
Memory based relational representation of data.
Part of the disconnected environment.
Present in System.Data namespace  DataSet class
DataTableCollection DataRowCollection DataColoumnCollection DataTable DataRelationCollection

Connection:
Data.SqlClient namespace  SqlConnection class
 Property: ConnectionString  Parameters: Provider, Data Source {server name}, Initial Clatalog
{database},User ID Password Integrated Security {determine whether or not connection needs to be
secure}
 Methods: Open() Close()
 Enumeration: ConnectionState [Broken, Close, Open, Fetching, Executing, Connecting]
 Events: StateChange InfoMessage

SqlConnection con = new SqlConnection();


Con.ConnectionString = “Data Source = SQLSERVER01; Initial Catalog = HR; User ID = sa; Password = niit123”;
Con.Open();
SqlCommand cmd = new SqlCommand(“select * from monthlysalary”, con);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
con.Close();

Con.StateChange += new StateChangeEventHandler(OnStateChange);


Protected static void OnStateChange (object sender, StateChangeEventArgs args)
{ Console.WriteLine(“The current connection state has changed from {0} to {1}”, args.OriginalState,
args.CurrentState); }

Con.InfoMessage += new SqlInfoMessageEventHandler(OnInfoMessage);


Protected static void OnInfoMessage (object sender, SqlInfoMessageEventArgs args)
{ foreach ( SqlError err in args.Errors) { Console.WriteLine(“The {0} error has occurred\n”+err.Message); } }
Retrieving data from SQL Database:
Project type : VC# Templates: windows application
DataGridView control (for tabular format, with or without any underlying data source)  right click – choose data
source, ad project data source, Data Source Configuration Wizard – choose data type – database – choose your data
connection – new connection, add connection, test connection, ok – Connection String – Save the connection to
application configuration file – choose your database objects – tables – finish. Right click again, edit coloums – ok.
F5 or debug.

DATA BINDING: Binding data source(database, arrays, collections) to control of a windows form
Simple Data Binding: binding a single value in a dataset to a text box or label [ To connect to database – Data 
Add New Data source which open the wizard of that earlier chapter, then Windows Form’s properties 
DataBindings property, Text Property, Add Project Data Source, F5 ]
Complex Data Binding: Binding more than one element and more than one record in the database to a control like
ListBox {1,2}, ComboBox{1,2}, DataGridView{1}.
1. DataSource property – bind to data source 2. DisplayMember property – bind to specific data element
 BindingNavigator – keeps a pointer to the current item.
Buttons: bindingNavigatorAddNewItem, bindingNavigatorDeleteItem, bindingNavigatorMoveFirstItem,
bindingNavigatorMoveLastItem, bindingNavigatorMoveNextItem, bindingNavigatorMovePreviousItem
TextBoxes: bindingNavigatorPositionItem, bindingNavigatorCountItem.
* Buttons for ‘add’ and ‘delete’ need coding
 BindingSource – navigate thorugh records on a form and interact and modify them
 BindingContext of the BindingManagerBase class – navigate and keep track of existing items. Manages
bindings of a form to the same data source. There is at least one binding context object for each form.
FILTERING DATA:
 Parameterized Queries: data can be filtered based on the criterion entered by the user at run time. Secure way
where database operations can be executed on the SQL server.
SqlConnection con = new SqlConnection();
Con.ConnectionString = “Data Source = SQLSERVER01; Initial Catalog = HR; User ID = sa; Password = niit123”;
Con.Open();
String searchemployeecode;
Searchemployeecode = textBox1.Text;
SqlCommand cmd = new SqlCommand(“select * from monthlysalary”, con);
cmd.Parameters.Add(new SqlParameter (“@employeecode”, searchemployeecode));
SqlDataReader dr = cmd.ExecuteReader();

 Using Windows Form: DataGridView – icon > . – AddQuery option – SearchCriterion Builder window –
Query Builder button – Execute Query button – ok – FillByToolStrip is added to the DataGridView control –
F5 or debug. Repeat procedure and add one FillByToolStrip for each query you want to pass.

Table Adapter Queries are SQL statements or stored procedures that an application can execute against a
database.
In the Search Criterion Builder window, the new query name is FillBy by default, but it can be changed

 DataView control: Set the properties for the control – AllowDelte, AllowAdd, AllowEdit, ApplyDefaltSort,
Modifiers[visibility level of DataView control], RowFilter, RowStateFilter[version of data], Sort,
GenerateMember, Table[specify data table that the control refers to, can be set at design or run time]

CONNECTED ENVIRONMENT
+tv Data current & updated, concurrency issues easier to control -tv network trafficking, slow query executn, etc
Command Object: DML statement or stored procedure used to retrieve, insert, delete, modify data in a data
source. It is an instance of the OleDbCommand or SqlCommand class.
Asynchronous: Simultaneous execution enhances overall performance & responsiveness. Uses SqlCommand class.
Methods – BeginExecuteNonQuery(does not return rows) BeginExecuteReader(returns rows)
BeginExecuteXmlReader(returns XML Reader object) EndExecuteNonQuery() EndExecuteReader(returns
SQLReader object) EndExecuteXmlReader(returnd XML data)
MultipleActiveResultSets (MARS) – feature is disabled by default. Can be activated by
String connection string = “Data source=SQLSERVER01; …….MultipleActiveResultSets=True”;
If you try executing a cmd when already 1 is being executed, DbReader object throws InvalidOperationException
message stating There is already an open datareader associated with this connection which must be closed first.
Can be avoided by using MARS - can execute multiple commands / queries using the same single connection.

Synchronous Operations: command objects are linked to each other, sequential execution, and if a command
object is deleted those objects connected to it also are deleted so linked object cannot perform independently

DbCommnd –DML or DDL command DbParameters – assign DbDataReader – Retrives in fwd


SqlConnection con = new SqlConnection(); parameterized values to stored only or read only mode. Its Read()
Con.ConnectionString = “Data Source… procedures method allows access to only one
Password”; ….con.Open();
Con.Open();
row at a time which means that data
String str = “select * from manthsal where need not be completely read into the
SqlCommand cmd = con.CreateCommand(); ccode = @val”;
cmd.CommandType=CommandType.Text SqlCommand cmd = new …..
application before it is processed.
cmd.CommandText = “select * from SqlParameter sql; SqlDataReader dr = cmd.ExecuteReader();
Production.Product where..”; Sql = cmd.Parameters.Add(“@val”, While(dr.Read())
cmd.ExecuteNonQuery(); SqlDbType.VarChar,15); { console.WriteLine(dr[0] + “” + dr[1]); }
Properties: CommandText sql.value=val; Properties: Depth FieldCount
CommandTimeout CommandType {parameter names and names in HasRows IsClosedItem
Connection Container stored procedures must match} RecordsAffected VisibleFieldCount
DesignTimeVisible Parameters Site Properties: DbType, Direction, Methods: Close() CreateObjRef()
Transaction UpdateRowSource IsNullable, ParameterName, Size, Dispose() Equals() GetHashCode()
Methods: Cancel() CreateObjREf() SourceCoulumn, SourceVersion, GetLifeTimeService() GetType()
Dispose() Equals() SourceColoumnNullMapping,Value InitializeLifeTImeService()
ExecuteNonQuery() ExecuteReader() Methods: CreateObjRef() Equals() IsDBNull() Read()
ExecuteScalar() GetHashCode() GetHashCode() ReferenceEquals() ReferenceEquals() ToString()
GetLifeTImeService() GetType() GetLifeTimeService() GetType()
InitializeLifeTimeService() Prepare() InitializeLifeTimeService()
ReferenceEquals() ToString() ResetDbType() ToString()
Data Adapters: Database  Data Adapter  Dataset. To retrieve, insert, delete and modify data.
Types: SqlDtaAdapter, OledbDataAdapter, OdbcDataAdapter, OracleDataAdapter
4 Properties: SelectCommand, InsertCommand, DeleteCommand, UpdateCommand – all these affect dataset
2 methods: Fill() Update()Reflects the changes made by delete, insert and update command properties on database.
DataSet dataset1 = new DataSet(); DataSet dataset1 = new DataSet(Employees);
SqlDataAdapter da = new SqlDataAdapter(); SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand(“Select * SqlCommand cmd = new SqlCommand(Select * from.. con);
from…”,con); da.SelectCommand = cmd;
da.SelectCommand = cmd; da.Fill(dataset1, Employees);
da.Fill(dataset1); da.Update(ds, Employees);
da.Update(ds); Employees is optional – name by which table will be known in database
SqlCommandBuilderClass automatically generates single table commands that are used to reconcile changes made
to a datasaet with the associated sql server database.
SqlCommandBuilder cb = new SqlCommandBuilder(da);

TableMappingsProperty – to change column names for better readability. There is one DataTableMapping object
defined for each set of mapped tables.

After making the changes in the data table through a data adapter, you need to ensure that changes are committed
and updated in the database.
Data conflicts: can be resolved by prioritizing on time (FIFA, LIFA), on role, on location, user resolves conflict. In
case both users have same role or location then fallback on prioritized by time.
To increase performance, use UpdateBatchSize property of of the SqlDataAdapter object. By default its set to 1.
Group of updates fired together – batch update. Use RowsUpdated event to find out if changes are being sent to
database server. RowsAffected changes according to the value of UpdateBatchSize property.
 The StringBuilder class converts string to SQL and SQL into string – mutable string of characters.
 The DbProviderFactories class (from the System.Data.Common) create provider specific objects. It contains
a method GetFactoryClasses() that returns a datatable populated with data from various providers.
DataTable providerList = null;
providerList = DbProviderFactories.GetFactoryClasses();
DataGridView1.DataSource = providerList;
DataSet – memory based relational representation of data – disconnected cached set of records retrieved from
database – virtual database containing tables, rows and columns.
TYPES  A typed dataset is derived from the DataSet class and has an associated XML schema.
string custid;
custid=DSCust.CustomerTracking[0].CustID; //storing value of CustID column, first row, CustomerTracking table,DSCust Dataset
An untyped dataset does not have any associated XML schema thus its structure is not known during
compliation. Thus it does not support Intellisense and auto completion of the syntax. Representation is in form of
collections.
string custid;
OleDbDACust.Fill(DSCust);
Custid=(string)(DSCUst.tables[“CustomerTracking”].Rows[0].Item[“CustID”]);

Implementing Datasets
DataSet ds = new DataSet;
DataTable dt = new DataTable();
dt = ds.Tables.Add();
dt.columns.Add(“StreID”, typpeof(string));

 By using a DataRow object the following methods can be performed on a row - Add() appends at tables end,
InsertAt(), Find() by primary key value, Select() by a condition, Remove() removes specified datarow object,
RemoveAt() removes row at a specified position, Delete() removes a row provisionally from a table.
 A DataSet.Relations property gets the collection of relations (PK, FK etc) that link tables and allow to navigate
from Parent to Child tables. Refer to page 3.34
----------------------------------------------------------------------------------------------------------------------------------------
LOBs are of different formats. Binary - BLOB or character - CLOB
Retrieving BLOB data. – normally DataReader object reads one row at a time. To access as a stream -
command.ExecuteReader(CommandBehaviour.SequentialAccess); allows access to columns which store large
binary data. After retrieval need to be converted to an array of bytes by using GetBytes() of the DataReader class.
Can write the BLOB data to the database by executing INSERT or UPDATE statement. Pass data as string
parameter if its text format and pass as binary parameter if its binary format. To reduce amount of memory used
write BLOB as chunks. To update existing data in chunks use UPDATETEXT. It requires a pointer to the BLOB
field being updated using Sql Server TEXTPTR function.
Format - UPDATETEXT<Table Name>.<Column Name><Pointer><Offset><Delete_Length>{if 0 is passed no
data is deleted , if null is passed all data is deleted}<Data>{refers to new data to be inserted}
cmd.CommandText = “Select TEXTPTR(PatientPhoto) from Patients where PatientId = ‘1004’”;
…….
SqlParameter ptrParm = cmd.Parameter.Add(“@Pointer”, SqlDbType.Binary,16):
ptrParm.Value=photoPtr;
SqlParameter photoParm = cmd.Parameters.Add(“@Data”,SqlDbType.Int);
offsetParm.Value=0;

BULK COPY operations like creating backup of a table: SqlBulkCopy class.


Parameters of WriteToServer(): DataRow[] copies all rows from DataRow array to destination table, DataTable[]
from datatable to destination table, IDataReader[] from IDataReader interface to destination table, (DataTable,
DataRowState) copies only rows that match the row state from the data table.
By default bulk copy is performed as isolated operation, in a non transacted way, with no chance for rolling back.
STEPS: connect to source server, connect to destination server, create a SqlBulkCopy object, set the
DestinationTableName property and call the WriteToServer() method of the SqlBulkCopy class itself.
Data types of source and destination column must match else class tries conversion which affects performance.
Structure of table to be created beforehand or error msg “cant access destination table ‘Patients_Backup”
Multiple bulk copy operations can also be done using the SqlBulkCopy class’s single instance.

SQL NOTIFICATION - Service Broker is a msg based communication platform to maintain reliable query
processing and asynchronous communication. Based on this infrastructure is SQL Notification – it notifies when
the database has been updated and thus the cache has expired (as cache will no longer match the database). To use it
– service broker needs to be enabled for the database (by default its not enabled) and the user ID connecting to the
DB needs to have the necessary permissions.
ALTER DATABASE HR SET ENABLE_BROKER;
CREATE QUEUE ConactChangeMessages; // QUEUE -primary message storage for messages exchanges by two services
CREATE SERVICE ContactChangeNotification ON QUEUE ContactChangeMessages
([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotifications1]);
When Queue receives a msg it calls an associated stored procedure(service that provides the functionality)
to process it. A service is used by the service broker to deliver the msg to the correct queue or route a msg to
another Db. “http:…” is the contract b/w the services on what type of msg will be transferred. The URL is an object
name actually not a real URL.
To execute SQL notifaction commands a user needs permissions on the database server.
USE DATABASE_NAME
GRANT SUBSCRIBE QUERY NOTIFICATION TO database_principal
Client side code requires permission too to ensure user has security level adequate to access data source.
System.Security.Permissions namespace;
private bool CanRequestNotifications()
{ SqlClientPermission perm = new SqlClientPermission(PermissionState.Unrestricted{PermissionState.None give no access};
try { perm.Demand(); return true; } catch(System.Exception) {return false;} }
Demand() forces a runtime SecurityException if all callershigher in the call stack have not been granted the permission.

Execute SQL Notification: SqlDependency class is used to process notifications. It automatically starts a worker
thread to process notifications as they are posted to the queue. Also parses the service broker msg and exposes the
msg as an event argument data. Class is initialized by SqlDependency.Start(connectionstr); //start is static method
called once at initilization. SqlDependency.Stop(connectionString); // stop called for each connection established.
Transaction – sequence of operations. If successful then commit() or else rolled back without affecting database.
Properties: ACID – Atomicity(all or none modifications done), Consistency – data integrity, Isolation of data mod.
Of 1 transaction from data mod. Of other, Durability – modifications are permanent even if system failure occurs as
backups of both, data and transaction logs, are kept.
Types – Local: on 1 data source, easy, efficient, System.Transactions nmspc. Distributed: on multiple data sources,
multiple connections, enables to pack various transactions into 1 unit which will either fail or succeed completely.
Local – implement IDbTrnsaction interface. Classes – Sys.Data.SqlClientTransaction ~Oracle
Sys.data.Odbc.OdbcTransaction ~OleDb.
using System.Data.SqlClient;
Using SystemTransaction;
SqlTransaction tran – null;
Tran = cn.BeginTransaction;
SqlCommand cmd = new SqlCommand)”insert…”, cn, tran);
cmd.ExecuteNonQuery();
catch (SqlExcepion ex)
{tran.RollBack();
Console.WriteLine(“error – transaction rolled back”+ ex.Message); ……

Distributed – System.Transactions nmspc. In the using block create a TransactionScope object. It is used to open
multiple connections within the same transaction. By default creates local transaction, when more than one
connection is established it creates a distributed transaction. That’s transaction promotion. In a distributed
transaction if an exception is thrown within the trnsactionscope object its rolledbacked or else Complete() is called
which commits the transaction.
Operations that can be performed within distributed transactions:
1. Bulk copy – Bulk copy is performed as part of a transaction (by default its isolated but it can be made as
part of a transaction). The operation creates and then commits or rolls back a transaction.
2. Specify the isolation level -

Potrebbero piacerti anche