E3106741667 Advanced C# Page 1 of 11 Chapter 21 Connecting to the database Executing Commands – ADO.NET Stored Procedures The ADO.NET object model Using XML and XML schemas – ADO.NET is built upon an XMLframework E3106741667 Advanced C# Page 2 of 11 ADO .NET a new approach ADO.NET ships with 2 client namespaces – One for SQL Server The other for database exposed through an OLE DB interface Namespaces System.Data = all generic data access classes System.Data.Common – Classes shared (or overridden) by individual data providers System.Data.OleDb – OLE Db provider classes System.Data.Sqlclient – SQL Server provider classes System.Data.SqlTypes – SQL Server data types E3106741667 Advanced C# Page 3 of 11 Shared classes a number of classes regardless of whether program is using SQL Server or OLE DB classes System.Data Namespace: DataSet - The object may contain a set of DataTables, can include relationships between these tables, and is designed for disconnected use DataTable – A container of data. Da DataTable consists of one or more DataColumns, and when populated will have one or more DataRows containing data DataRow – A number of values – a row from the table or spreadsheet DataColumn – Contains the definition of a column, name and data type DataRelation – A link between two DataTables within a DataSet. Constraint – Defines a rule for a DataColumn ( or a set of Data Columns), such as unique values System.Data.Common Namespace DataColumnMapping – Maps the name of a column from the database with the name of a column within a DataTable DataTableMapping – Maps a table name from the database to a DataTable within a DataSet E3106741667 Advanced C# Page 4 of 11 Database Specific Classes Implement a set of standard interfaces defined within the Syste.Daata namespace SqlCommand, OleDbCommand – Awrapper for SQL statements or stored procedure calls SqlCommandBuilder, OleDbCommandBuilder – A class used to generate SQL commands ( such as INSERT, UPDATE, an DELETE statements) from a SELECT statement SqlConnection, OleDbConnection – The connection to the database. SqlDataAdapter, OleDbDataAdaper – A class used to hold select, insert, update and delete commands, which are then used to populate a DataSet and update the Database SqlDataReader, OleDbDataReader – A forward only, connected data reader SqlParameter, OleDbParameter – Defines a parameter to a stored procedure SqlTransaction, OleDbTransaction – A database transaction, wrapped in an object Most important feature – ADO.NET is designed to work in a disconnected manner E3106741667 Advanced C# Page 5 of 11 Using Database Connections How to create, open and close a connection using System.Data.SqlClient // parameters are delimited by semicolon string source = “server=(local)\\NetSDK;” + “uid=QSUser;pwd=QSPassword;” + “databae=Northwind”; SqlConnection conn = new SqlConnection(source); Conn.Open(); // do something conn.Close(); Using Connections Efficiently Keeping sessions open too long can affect other applications Closing should be considered mandatory Two main ways to ensure database connections (or other resources) are release: try – catch and finally block using block E3106741667 Advanced C# Page 6 of 11 Lab 6b string source = "server=HOME\\NetSDK;" + "integrated security=SSPI;" + "database=Northwind"; SqlConnection conn = new SqlConnection(source); // make sure data base gets closed try { // open connection conn.Open(); // Do something MessageBox.Show("Data base is opon"); } catch (Exception ex) { // do something } finally { MessageBox.Show("Data Base is clsoing"); conn.Close(); } // // // // The using Block ensures that the data base connection is closed in addtion if the using block is used within the try block and an exception occurs the Idisoposable.Dispose method will be called on the resource guarded by the using clause try { string source2 = "server=HOME\\NetSDK;" + "integrated security=SPPI;" + "database=Northwind"; using (SqlConnection conn2 = new SqlConnection(source2)) { conn2.Open(); MessageBox.Show("using block"); // do something // close myselft - optional since Close will be called } } catch (Exception e2) { // dos something MessageBox.Show("in catch Block"); } finally { // ensure close MessageBox.Show("In finally block"); conn.Close(); } E3106741667 Advanced C# Page 7 of 11 Transactions Updates within the scope of a transaction string source = "server=HOME\\NetSDK;" + "integrated security=SSPI;" + "database=Northwind"; SqlConnection conn = new SqlConnection(source); conn.Open(); SqlTransaction tx = conn.BeginTransaction(); // execute command tx.Commit(); conn.Close(); Isolation Levels – determines how changes are made in one database session are viewed by another – (page 692) E3106741667 Advanced C# Page 8 of 11 Commands string source = "server=HOME\\NetSDK;" + "integrated security=SSPI;" + "database=Northwind"; string select = “SELECT ContactName, CompanyName FROM Customers”; SqlConnection conn = new SqlConnection(source); conn.Open(); SqlCommand cmd = new SqlCommand(select ,conn); Command Type enumerations Text (default) StoredProcedure TableDirect Set command type: cmd.CommandType = …. Exucuting commands ExecuteNonQuery() – Executes the command but dows not return any output ExecuteReader() – Executes the command and returns a typed IdataReader ExecuteScalar() – Exeucctes the command and returns a single value The SqlCommand class aso exposes the method ExecuteXmlReader() – Executes the command and returns an XmlReader object, which can be used to traverse the SML fragment returned from the database E3106741667 Advanced C# Page 9 of 11 Fast Data Access: The Data Reader The data reader is the simplest and fastest way of selecting some data from a data source However, it has the least capabilities Cannot directly instantiate a data reader object –an instance is returned from the appropriate databe’s command object (ex SqlCommand) after having called the ExcuteReder() method Keeps the database open until it is closed E3106741667 Advanced C# Page 10 of 11 using System; using System.Data.OleDb; public class DataReader { public static int Main(string[] args) { string source = "Provider=SQLOLEDB;" + Login.Connection ; string select = "SELECT ContactName,CompanyName FROM Customers" ; OleDbConnection conn = new OleDbConnection ( source ) ; try { conn.Open ( ) ; OleDbCommand cmd = new OleDbCommand ( select , conn ) ; OleDbDataReader aReader = cmd.ExecuteReader ( ) ; while ( aReader.Read ( ) ) Console.WriteLine ( "'{0}' from {1}" , aReader.GetString(0) , aReader.GetString ( 1 ) ) ; aReader.Close ( ) ; conn.Close ( ) ; } catch ( Exception e ) { Console.WriteLine ( e ) ; Console.WriteLine ( ) ; Console.WriteLine ( "Chances are your database does not have a user" ) ; Console.WriteLine ( "called QSUser, or you do not have the NetSDK “ + “ database installed." ) ; } return 0; } } E3106741667 Advanced C# Page 11 of 11 The DataSet