Vous êtes sur la page 1sur 13

279 ADO.NET It is a collection of Managed Providers that can be used for communication with Data Sources.

-> When .NET was designed for Data Source communication ADO.NET has been designed, which is an extension to the Older ADO (Collection of Unmanaged Providers). -> ADO.NET provides various 'types' that can be used for data source communication under the following namespaces. 1) System. Data 2) System.Data.OleDb 3) System.Data.SqlClient 4) System.Data.OracleClient 5) System.Data.Odbc System. Data Types under this namespace are used for holding and managing of data on Client machines. 'Classes'under this namespace are DataSet, DataTable, DataColumn, DataRow, DataView, DataRelation etc. System.Data.OleDb Types under this namespace are used for communicating with any data source like Files, Databases,and IndexingServers etc. System.Data.SqlClient Types under this namespace are used only for Sql Server Database communication. System.Data.OracleClient Types under this namespace are used only for Oracle Database communication. System.Data.Odbc Types under this namespace are used for communicating with traditional Odbc drivers and they will in turn communicate with any data source. All the above four namespaces contains same set of Classes as following.-

-Connection -Command -DataReader -DataAdapter -CommandBuilder -Parameter Note: - Each 'class' here is referred by prefixing with their namespace before 'class' name to discriminate between each other as following. -OleDbConnection -SqlConnection -OracleConnection -OdbcConnection OleDbCommand SqlCommand -OracleCommand OdbcCommand

Each and every operation we perform on a data source has three steps in it. 1) Establishing a Connection 2) Sending request as a Statement 3) Capturing the results given by DataSource 1)Establishing a Connection In this process we open a channel for communication with the DataSource present onlocal or remote machine to perform the operations. To open a channel for communication we use'Connection' class. Constructors Connection () Connection (string connectionstring) 'Connectionstring' is a collection of attributes that are used for connecting with a data source those are 1) Providers 2) DataSource 3) User Id and Password 4) Database (or) Initial catalog 5) Trusted_Connection = True

6) DSN 1) Provider As we discussed earlier a Provider is required for communicating with Data sources, where we need to use different Provider for different Data Source. Oracle Msdaora SqlServer SqlOleDb MS-Access (or) MS-Excel Microsoft.Jet.OleDb.4.0 IndexingServer Msidxs 2) DataSource It is the name of target machine to which we want to connect with doesnt require to be specified if data source is on local machine only. 3) User Id & Password As Databases are secured places for storing data, to connect with them we require a valid Username and Password. Oracle SqlServer Scott/tiger Sa/<pwd>

4) Database (or) Initial catalog These attributes are used while connecting with SqlServer to specify the name of Database, we need to connect with. 5) Trusted_Connection (or) Integrated Security These attributes are used while connecting with SqlServer to specify that we want to use 'Windows Authentication'. 6) DSN This attributes are used to connect with a data source using 'Odbc' drivers. Connection String for Oracle "Provider=Msdora ; User Id=Scott; Password=tiger [; DataSource=<server>]"

Connection String for SQLServer "Provider=SqlOleDb; User Id=Sa; Password=<pwd>; Database=<db name> [; Datasource=<server>]" Methods and Properties of Connection Class 1) Open () -> Opens a connection with data source 2) Close () -> Close the connection which is open 3) State -> Gets the status of Connection 4) Connectionstring -> Gets or Sets a connectionstring associated the connection object. -> The object of class Connection can be created in any of the following ways Connection con=new Connection (); Con.ConnectionSting="<con str>"; * Open a new Project of type Windows and name it as "DBOperations". -> Create the 'Form' as following.

usingSystem.Data.OleDb; Under Connect with Oracle button: OleDbConnectionoracon =new OleDbConnection("Provider=Msdora;User Id=Scott;Password=tiger"); oracon.Open(); MessageBox.Show(oracon.State.ToString()); oracon.Close(); MessageBox.Show(oracon.State.ToString()); Under Connect with SQL button: OleDbConnectionsqlcon =new OleDbConnection("Provider=SqlOleDb; User Id=Sa; Password=123;Database=mydb; Data Source=praveen"); sqlcon.Open(); MessageBox.Show(sqlcon.State.ToString()); sqlcon.Close(); MessageBox.Show(sqlcon.State.ToString()); Sending request as a Statement In this process we send a request to Data source specifying the type of action we want to perform using a Sql Statement like Insert, Update, Delete and Select. 'Command' class is used for sending request and executing of the statements. Command () Command (string sqlstmt, Connection con)

Properties of Command class 1)Connection: Sets or gets the connection object associated with Command. 2)CommandText: Sets or gets the statement associated with Command. Object of class 'Command' can be created in any of these following ways. Command cmd = new Command (); cmd. Connection=<con>; (or) Command cmd=new Command ("<sql stmt>",con); Methods of 'Command' Class ExecuteReader () ---> DataReader ExecuteScalar () ---> object ExecutNonQuery () ---> int After creating the object of 'Command' class we need to call any of these three methods to execute the statement. -> Use 'ExecuteReader' method when we want to execute a 'Select' statement that returns data as Rows and Columns. The method returns an object of class 'DataReader' which holds the data that is retrieved in the form of Rows and Columns. -> Use 'ExecuteScalar' method when we want to execute a 'Select' statement that returns a single value result. Return type of this method is object, which gets the value in a generic type.

-> Use 'ExecutNonQuery' method when we want to ExecutNonQuery statements (DML statements like Insert, Update and Delete). In this case we need to find out the number of Rows affected by the statement and also the return type of the method is an 'int'. Note: - The above process of calling an appropriate method in the appropriate case is our third step capturing of the results. Accessing Data from DataReader DataReader is a class which will hold the data in the form of Rows and Columns (Table Structure). Toaccess data from DataReader it provides us following methods. 1) Read () -> bool Move record 'Pointer' from the current location to next row and returns a Boolean status which tells whether the row to which we have moved contains data in it or not. That will be 'true' if present or 'false' if not represent. 2) GetValue (int index) -> object Used for retrieving field values from the row to which 'pointer' was pointing by specifying the Column index position. Note: - We can access the row pointer by pointer in the form of a single Dimensional array also eitherby specifying column index position or name as following. <DR> [index] -> object <DR> [column name] -> object

3) GetName (int index) -> string Returns the name of column for given index position.

4) NextResult () -> bool Moves the record pointer from current table to next table if a table exists and returns true or else returns false.

usingSystem.Data.OleDb; Declarations: OleDbConnectioncon; OleDbCommandcmd; OleDbDataReaderdr;

Under Form Load: con =new OleDbConnection("Provider=Msdaora;User Id=Scott;Password=tiger"); cmd =new OleDbCommand("Select Deptno,Dname,Loc From Dept", con); con.Open (); dr = cmd.ExecuteReader(); label1.Text = dr.GetName (0); label2.Text = dr.GetName (1); label3.Text = dr.GetName (2); ShowData ();

private voidShowData() { if (dr.Read()) { textBox1.Text = dr.GetValue (0).ToString (); textBox2.Text = dr.GetValue (1).ToString (); textBox3.Text = dr.GetValue (2).ToString (); } else MessageBox.Show ("Last Record"); } Under Next button: ShowData (); Under Close button: if (con.State !=ConnectionState.Closed) con.Close (); this.Close ();

-> Set Deptno TextBox 'ReadOnly' property as 'true'

usingSystem.Data.OleDb; Declarations: OleDbConnectioncon; OleDbCommandcmd; OleDbDataReaderdr; stringsqlstr; Under Form Load: con =new OleDbConnection("Provider=Msdaora;User Id=Scott;Password=tiger"); cmd =new OleDbCommand(); cmd.Connection = con;

LoadData (); private voidLoadData() { sqlstr ="Select Deptno,Dname,Loc From Dept Order By Deptno"; SetStmt (); dr = cmd.ExecuteReader(); ShowData (); } private voidSetStmt() { if (con.State !=ConnectionState.Closed) con.Close (); cmd.CommandText = sqlstr; con.Open (); } private voidShowData() { if (dr.Read()) {textBox1.Text = dr [0].ToString (); textBox2.Text = dr [1].ToString (); textBox3.Text = dr [2].ToString (); } else MessageBox.Show ("Last record of the Table"); } private voidExecuteDML() { DialogResultd =MessageBox.Show (sqlstr +"\n\nDo you wish to execute the Query?","Confirmation",MessageBoxButtons.YesNo,MessageBoxIcon.Question); if (d ==DialogResult.Yes) { SetStmt (); Int Count = cmd.ExecuteNonQuery(); if (Count > 0) MessageBox.Show ("Statement Executed Successfully"); Else MessageBox.Show ("Statement Execution Failed"); LoadData (); }

} Under Next button: ShowData (); Under New button: textBox1.Text = textBox2.Text = textBox3.Text =""; sqlstr ="Select Max(Deptno) + 10 From Dept"; SetStmt (); textBox1.Text = cmd.ExecuteScalar ().ToString (); textBox2.Focus (); Under Insert button: sqlstr=String.Format("Insert Into Dept (Deptno,Dname,Loc) Values({0},'{1}','{2}')", textBox1.Text, textBox2,Text, textBox3.Text); ExecuteDML (); Under Update button: sqlstr=String.Format ("Update Dept Set Dname='{0}', Loc='{1}' Where Deptno= {2}", textBox2.Text,textBox3.Text, textBox1.Text); ExecuteDML (); Under Delete button: sqlstr =String.Format("Delete From Dept Where Deptno= {0}", textBox1.Text); ExecuteDML (); Under Close button: if (con.State !=ConnectionState.Closed) con.Close (); this.Close ();