Presentation is loading. Please wait.

Presentation is loading. Please wait.

C# .NET Software Development

Similar presentations


Presentation on theme: "C# .NET Software Development"— Presentation transcript:

1 C# .NET Software Development
ADO.NET C# .NET Software Development

2 ADO.NET Interfaces to and programmatically works with databases
Provides an abstraction layer between the database and the user Simplifies and standardizes how data connections are handled Data manipulation is done in a disconnected environment. This is accomplished by connecting to the database for just long enough to retrieve the data and store it in a local cache. The data is stored in a memory cache on the client machine and manipulated there. A disconnected environment promotes scalability.

3 ADO.NET Objects ADO.NET Objects include: DataConnection DataAdapter
Command DataReader DataSet DataTable DataColumn DataRow DataRelation

4 ADO.NET Client Database DataAdapter Command DataReader Connection
Disconnected DataSet (In-Memory) Client DataAdapter Command DataReader Connection Database

5 Getting The Data To get the data into local cache:
A connection is established Data is transferred from the database The connection is closed To create the connection using a data connection object: Connection objects implement the IDbConnection interface The connection objects themselves are specific to the database being connected to SqlConnection SqlCeConnection OracleConnection OdbcConnection OleDbConnection

6 Connection String When creating an SqlConnection object, pass it a connection string that gives the object information about the connection. Some of the possible entries in the connection string are: For the complete list of possible entries, see SqlConnection.ConnectionString Property in the MSDN documentation. Entry Explanation Database The name of the database to connect to Server The URL of the server to connect to User ID The User ID to use to log into the database Password The password of the user logging in Encrypt Set true to encrypt all data between the client and the database

7 Example Connection String
The creation of an SqlConnection object looks like the following: the connection string contains various entries separated by semi-colons The order of the entries does not matter SqlConnection conn = new SqlConnection( "Database=northwind; server=localhost; user id=demo; password=demo");

8 Establishing a Connection
To connect to the database, the code looks like the following: To close the connection invoke the Close method: Some ADO.NET constructs open and close the connection for you The rule is if you open it, you close it You should close the database in a finally block conn.Open(); conn.Close();

9 DataSet The DataSet class models a relational database in memory.
It is the local cache Tables are represented by the DataTable class DataTables are made up of DataColumns DataRows Constraints can be placed upon columns in DataTables Relationships between tables can be created In the System.Data namespace

10 DataSet Pictorially:

11 DataSet In Code: DataSet ds = new DataSet("MyDataSet");
DataTable dt1 = new DataTable("Persons"); ds.Tables.Add(dt1); // Initialize Table dt1.Columns.Add(new DataColumn("Name", typeof(string))); dt1.Columns.Add(new DataColumn("Age", typeof(int))); dt1.Columns.Add(new DataColumn("Salary", typeof(decimal))); // put some rows in Table dt1.Rows.Add(new object[] { "Sheldon", 31, m }); dt1.Rows.Add(new object[] { "Kurt", 28, m }); dt1.Rows.Add(new object[] { "Mike", 23, m }); dt1.Rows.Add(new object[] { "Dennis", 145, m });

12 Accessing Data in the DataSet
The previous example creates a dataset and populates it with a table. The DataSet is created with the name "MyDataSet" that is passed to the constructor. A table is created named "Persons", once again the name is passed in the constructor. We can access an entry in the table as follows: ds.Tables["Persons"].Rows[0]["Name"] = "Edgar";

13 Column Constraints Constraints are restrictions that are applied to DataColumns AllowDBNull Unique AutoIncrement DataColumn dc = new DataColumn("ID", typeof(int)); dc.Unique = true; dc.AutoIncrement = true; dc.AutoIncrementSeed = 10; dc.AutoIncrementStep = 2;

14 Data Relation A DataRelation defines a relationship between tables
The constructor of the DataRelation class takes name of the relation the parent column(s) the child column(s) The parent and child columns can correspond to primary key/foreign key relationship in a database DataRelation relation = new DataRelation( "CustomerOrderInfo", invoiceDS.Tables["Customers"].Columns["ID"], invoiceDS.Tables["Orders"].Columns["CustomerID"]); invoiceDS.Relations.Add(relation);

15 Data Relation The following example demonstrates how to exercise the relation on a DataRow from the previous example DataRow[] results = invoiceDS.Tables["Customers"].Rows[0].GetChildRows(relation);

16 Typed DataSets ADO.NET allows for strongly typed DataSets
The Typed DataSet allows for compile-time type checking With a Typed DataSet the syntax to index into a table is shortened You gain intellisense and autocomplete // Untyped DataSet access ds.Tables["MyTable"].Columns["Name"] // Corresponding Typed DataSet ds.MyTable.NameColumn

17 DataAdapter A DataAdapter acts as a bridge between the DataSet and the database DataAdapters are database specific

18 DataAdapter Use the DataAdapter to fill a DataSet
Note that the DataAdapter opens and closes the connection for you SqlConnection conn = new SqlConnection( "Database=northwind; server=localhost; user id=demo; password=demo"); DataSet ds = new DataSet(); SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Customers", conn); adapter.Fill(ds);

19 DataAdapter If the DataSet is modified, you can automatically update the database as follows: adapter.Update(ds);

20 Command Objects A Command object is a .NET class that contains a database command Command objects are database provider-specific There are three types of commands that the SqlCommand object can represent: Stored procedures SQL Commands Table-direct commands Not supported by MS SQL Server The type of the command is controlled by the CommandType property of the SqlCommand class

21 CommandType.Text The command object represents an SQL command
This is the default SqlCommand command = new SqlCommand( "SELECT * FROM Employees", connection); // this is the default, it is technically not needed command.CommandType = CommandType.Text; adapter.SelectCommand = command; adapter.Fill(dataSet);

22 CommandType.StoredProcedure
The command object represents a stored procedure SqlCommand command = new SqlCommand( "Ten Most Expensive Products", connection); command.CommandType = CommandType.StoredProcedure; adapter.SelectCommand = command; adapter.Fill(dataSet);

23 Stored Procedures Stored procedures are precompiled collections of SQL commands and flow-control statements that reside with the database in the DBMS Stored procedures can contain conditional logic (a normal SQL query cannot) The use of stored procedures reduces bandwidth use Stored procedures are precompiled, thus they have optimal execution. Stored procedures abstract the database from the programmer Stored procedures allow the DBA to manipulate the data and return a result set to the to the requesting method The programmer need not know the intricacies of the database Abstraction is good

24 Stored Procedures To access a Stored Procedure in ADO.NET, you must use a Command object You need to do the following to call a stored procedure using MS SQL Server: Create an SqlCommand object Set the CommandType property to CommandType.StoredProcedure Set the CommandText property to the name of the stored procedure. Set up the parameters for the stored procedure (if there are any). Invoke the stored procedure.

25 Stored Procedure Example
// create a dataset for the results DataSet dataSet = new DataSet(); // create a connection object SqlConnection connection = new SqlConnection( "Database=Northwind; Server=localhost; user id=demo; password=demo"); SqlCommand command = new SqlCommand("CustOrdersDetail", connection); command.CommandType = CommandType.StoredProcedure; // create a parameter object SqlParameter param = new SqlDbType.Int); param.Direction = ParameterDirection.Input; param.Value = 10254; // add the parameter to the parameter list for the command object command.Parameters.Add(param); // invoke the stored procedure and get the results SqlDataAdapter adapter = new SqlDataAdapter("CustOrdersDetail", connection); adapter.SelectCommand = command; adapter.Fill(dataSet);

26 Command Objects A Command object can also execute commands that go directly to the database with the following methods Method Description ExecuteNonQuery Executes non-select commands on the database and returns the number of rows affected ExecuteReader Executes a query and returns the result in a DataReader object. ExecuteScalar Executes a command on the database and returns one value. If the command returns one value, it is returned. If the command returns a table view, the value of the first column, first row is returned. ExecuteXmlReader Executes a query and returns the results in an XmlReader object.

27 DataReader The DataReader represents a read-only, forward-only set of rows from a database. DataReader classes are provider-specific connection.Open(); SqlCommand command = new SqlCommand( "select LastName from employees", connection); SqlDataReader reader = command.ExecuteReader(); while(reader.Read()) { Console.WriteLine(reader["LastName"]); } connection.Close();

28 DataView A DataView represents a filtered view of the data in a table or tables contained in a DataSet One of the major functions of the DataView is to allow data binding within both Windows and Web Forms adapter.SelectCommand = new SqlCommand("SELECT * FROM Products", connection); adapter.Fill(dataSet); DataView view = new DataView(dataSet.Tables[0]); view.RowFilter = "UnitPrice > and UnitPrice < 30.00"; 3

29 Data Binding DataBinding is the process of binding a data cache object, such as a DataSet or DataTable, to a visual control To bind assign the object to the control's DataSource property Some GUI controls are only designed to display a column of data and not an entire table. To limit what is displayed, set the controls DisplayMember property as follows: myDataGrid.DataSource = myDataTable; myListBox.DataSource = myDataTable; myListBox.DisplayMember = "Col Three";

30 Data Binding


Download ppt "C# .NET Software Development"

Similar presentations


Ads by Google