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

ADO.Net 2.

0
Aids in database connectivity

What Is Database Connectivity


Data used by the applications is stored in a database. This database is external to the application It is retrieved into the application as required by the program. This retrieval is achieved by writing the code that provides a link between the application & database. This link is known as database connectivity. This link is used to send the commands to the database & getting the corresponding results.

Role of Microsoft.Net
It has provided classes that aid in the database connectivity. All these classes are located in the System.Data namespace. These classes perform the following tasks  Communication with the database  Storing the data in the database  Fetching the data in the database  Updating the data in the database These classes makes the core data access objects in .NET Framework These are collectively known as ADO.NET

Required NameSpaces
ADO.NET ships with four database client namespaces
    System.Data.SqlClient System.Data.Oledb System.Data.Odbc System.Data.OracleClient

Shared Classes
ADO.NET contains a number of classes that are used irrespective of the namespace you are using to fetch data
      

DataSet DataTable System.Data DataRow DataColumn DataRelation DataColumnMapping System.Data.Common DataTableMapping

Database specific Classes


The following classes can be prefixed each with Oledb, SQL, Oracle, ODBC for respective database
       Command : wrappers for SQL statements or stored procedure calls. CommandBuilder: Used to generate SQL commands Connection: Used to connect to the database DataAdapter: Used to hold select, insert, update, and delete commands, which are then used to populate a DataSet and update the Database DataReader: Used as a forward only, connected data reader Parameter: Used to define a parameter to a stored procedure. Connection: Used for a database transaction, wrapped in an object.

Database specific Classes


The most important feature of the ADO.NET classes is that they are designed to work in a disconnected manner, which is important in today's highly Web-centric world. ADO 2.1 introduced the disconnected record set, which would permit data to be retrieved from a database, passed to the client for processing, and then reattached to the server. This used to be cumbersome to use, because disconnected behavior was not part of the original design. The ADO.NET classes are different in all but one case (the <provider>DataReader) they are designed for use offline from the database.

Connection
A representation of an open connection to the database It does not perform the following tasks  Doesnt fetch or update data  Doesnt execute queries A Connection object is  A pipeline that commands & queries use to send data & retrieve results It is a place to set the connection string

Connection
Command & Queries Connection Object Information from the data source & Returned data Database

Connection in Server Explorer


Visual Studio provides server explorer as the window to create connection This connection can be used in any project

Connections through Data Wizards


Data Source configuration wizard is used for building the database connection Using this wizard, you need to select the database path & you end up with a configured connection object ready to use in your application. Apart from that, the wizard also allows you to select the database objects you want to use in your application You can also bind your controls with different columns in the database. Binding is of two types
  Simple Binding : 1 Conrtol is bound to 1 column Complex Binding : 1 Control is bound to many columns

Different ways of fetching data


DataReader
 Stores a single row at a time in the memory  Requires a constant connection with the database

DataSet
 Stores one or more tables  Is a disconnected, cached set of records that are retrieved from the database

Connection Objects through Code


You can also create connection at runtime by writing the code to create Connection Object First of all, you need to select the type of connection you want. This choice depends on the database you are connecting communicating with
Name SQL Connection Oledb Connection ODBC Connection Oracle Connection Target Data Source SQL Server Database (2000 onwards) OLEDB data Source such as Access Use DSN Oracle databases

Connection Object
Each Connection Object contains the same base properties, methods & events that are inherited from the System.Data.Common.DbConnection class Properties

Connection Properties
Name ConnectionString Description Gets or Set the String to open the connection

ConnectionTimeout Gets the time to wait while establishing the connection before generating an error Database Gets the name of current database after connection is open or the database name specified in the connection string before the connection is opened Gets the name of database server to which it is connected Gets a string that represents the version of the server to which the object is connected Gets a string that describes the state of the connection

DataSource ServerVersion State

SQL Server 2005 Connection


The code to connect to SQL Server is: private SqlConnection sql = new SqlConnection (@"Data Source=user\sqlexpress;Initial Catalog=AdventureWorks;Integrated Security=True"); Or private SqlConnection sql = new SqlConnection(); sql.ConnectionString = @"Data Source=user\sqlexpress;Initial Catalog=AdventureWorks;Integrated Security=True";

Commands
A command is, in its simplest form, a string of text containing SQL statements that is to be issued to the database. A command could also be a stored procedure, or the name of a table that will return all columns and all rows from that table

Using Command
string source = @"Data Source=user\sqlexpress;Initial Catalog=AdventureWorks;Integrated Security=True"; string select = "SELECT ContactName,CompanyName FROM Customers"; SqlConnection conn = new SqlConnection(source); conn.Open(); SqlCommand cmd = new SqlCommand(select, conn);

CommandType
<provider>Command classes have a property called CommandType, which is used to define the type of command

CommandType Example
Text (default) String select = "SELECT ContactName FROM Customers"; SqlCommand cmd = new SqlCommand(select , conn);

StoredProcedure SqlCommand cmd = new SqlCommand("CustOrderHist", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@CustomerI D", "QUICK"); TableDirect OleDbCommand cmd = new OleDbCommand("Categories", conn); cmd.CommandType = CommandType.TableDirect;

Executing Commands
ExecuteNonQuery() Executes the command but does not return any output ExecuteReader() Executes the command and returns a typed IDataReader ExecuteScalar() Executes the command and returns a single value In addition to these methods, the SqlCommand class exposes the following method: ExecuteXmlReader() Executes the command and returns an XmlReader object, which can be used to traverse the XML fragment returned from the database.

ExecteNonQuery
Used for UPDATE, INSERT, or DELETE statements, where the only returned value is the number of records affected. This method can, however, return results if you call a stored procedure that has output parameters string select = "string select = "UPDATE Customers " + "SET ContactName = 'Bob' " + "WHERE ContactName = 'Bill'"; SqlCommand cmd = new SqlCommand(select, conn); int rowsReturned = cmd.ExecuteNonQuery(); Console.WriteLine("{0} rows returned.", rowsReturned);

ExecuteReader
This method executes the command and returns a typed data reader object, depending on the provider in use. The object returned can be used to iterate through the record(s) returned string select = "SELECT ContactName,CompanyName FROM Customers"; SqlDataReader reader = cmd.ExecuteReader(); while(reader.Read()) { Console.WriteLine("Contact : {0,-20} Company : {1}" , reader[0] , reader[1]); }

ExecuteScalar
Used to return a single result from a SQL statement, such as the count of records in a given table

string select = "SELECT COUNT(*) FROM Customers"; SqlCommand cmd = new SqlCommand(select, conn); object o = cmd.ExecuteScalar(); Console.WriteLine ( o ) ;

Calling Stored Procedures


Calling a stored procedure with a command object is
   a matter of defining the name of the stored procedure, adding a definition for each parameter of the procedure, then executing the command with one of the methods

Stored Procedure
The following stored procedure can be created in SQL Server 2005 This procedure updates the data in the table CREATE PROCEDURE RegionUpdate (@RegionID INTEGER, @RegionDescription NCHAR(50)) AS SET NOCOUNT OFF UPDATE Region SET RegionDescription = @RegionDescription WHERE RegionID = @RegionID GO

Calling the stored procedure from .Net Code


SqlCommand aCommand = new SqlCommand("RegionUpdate", conn); aCommand.CommandType = CommandType.StoredProcedure; aCommand.Parameters.Add(new SqlParameter ("@RegionID", SqlDbType.Int, 0, "RegionID")); aCommand.Parameters.Add(new SqlParameter("@RegionDescription", SqlDbType.NChar, 50, "RegionDescription")); aCommand.UpdatedRowSource = UpdateRowSource.None; aCommand.Parameters[0].Value = 999; aCommand.Parameters[1].Value = "South Western England"; aCommand.ExecuteNonQuery();

Procedure that returns output parameters


CREATE PROCEDURE RegionInsert(@RegionDescription NCHAR(50), @RegionID INTEGER OUTPUT) AS SET NOCOUNT OFF SELECT @RegionID = MAX(RegionID)+ 1 FROM Region INSERT INTO Region(RegionID, RegionDescription) VALUES(@RegionID, @RegionDescription) GO

Calling from .Net


SqlCommand aCommand = new SqlCommand("RegionInsert" , conn); aCommand.CommandType = CommandType.StoredProcedure; aCommand.Parameters.Add(new SqlParameter("@RegionDescription" , SqlDbType.NChar , 50 , "RegionDescription")); aCommand.Parameters.Add(new SqlParameter("@RegionID" , SqlDbType.Int, 0 , ParameterDirection.Output , false , 0 , 0 , "RegionID" , DataRowVersion.Default , null)); aCommand.UpdatedRowSource = UpdateRowSource.OutputParameters; aCommand.Parameters["@RegionDescription"].Value = "South West"; aCommand.ExecuteNonQuery(); int newRegionID = (int) aCommand.Parameters["@RegionID"].Value;

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