Professional Documents
Culture Documents
Ado Net
Ado Net
NET Framework
ADO.NET
ADO.NET deals with accessing Databases. Its a new technology that runs within the .NET environment. It uses the concept of managed code. ADO.NET provides access to data sources such as Microsoft SQL Server, OLE DB and XML. Applications connect to these data sources to access, manipulate or update data.
Writing into the database 1. Prepare the connection string, say myConnStr, which would contain the relevant information about the data store. An example would be: String myConnStr; myConnStr= "User ID=sa; Initial Catalog=Northwind;" + "Data Source=mySqlServer;Password=;"; OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=D:\\MCA\pro.mdb"); Be sure to substitute your user id, Sql Server name and password appropriately.
2. Instantiate a Connection object, say myConn as SQLConnection myConn = new SQLConnection(myConnStr);. Prepare the SQL string that will be used to extract necessary data from the data store, for example: String mySql; // build the sql query string mySql = "Insert into Product values(12,"wheat",20)"; try{ str="Insert into pro2(firstname,lastname) values('kailash','kandpal')"; 4. Instantiate a Command object by passing the connection object and the SQL string as follows: SQLCommand myCmd = new SQLCommand(mySql, myConn); OleDbCommand cmd = new OleDbCommand(str,cn);
5. Open the Connection, as myConn.Open(); cmd.Connection.Open(); cmd.Connection.Open(); 6. The final step is to execute the command with: myCmd.ExecuteNonQuery() cmd.ExecuteNonQuery(); cmd.Connection.Close(); } catch (Exception e1) { } }
Selection Example
public void ConnectToAccess() { System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(); // TODO: Modify the connection string and include any // additional required properties for your database. conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data source= C:\Documents and Settings\username\" + @"My Documents\AccessFile.mdb"; try{ conn.Open();// Insert code to process data. }catch (Exception ex){ MessageBox.Show("Failed to connect to data source");}finally{conn.Close();} }
Retrieving data from > 1 table or source requires a database JOIN Data is flattened : lose relationships; navigation is sequential
Data types are bound to COM/COM+ data types
Retrieving data from > 1 table or source does not require a JOIN Relationships are preserved: navigation is relational
Data types are only bound to XML schema No data type conversions required XML, like HTML, is plaintext: Firewall friendly
ADO.NET-related Namespaces
ADO.NET
System.Data
.SqlTypes
.SqlClient
.Common
.OleDb
Contains the main classes of ADO.NET In-memory cache of data In-memory cache of a database table Used to manipulate a row in a DataTable Used to define the columns in a DataTable Used to relate 2 DataTables to each other
Used to create views on DataSets
DataView
Relations
DataRelation DataRelation
DataColumn Constraint(s)
DataViewManager
DataTable DataTable
DataSet
Common client data store
DataSet Tables Table Columns Column Constraints Constraint Rows Row Relations Relation
An in-memory cache of data from a data source Common way to represent and manipulate data Universal data container Not just for use with databases Logical or physical representation of data Designed to be disconnected from the data source Connect, execute query, disconnect Can use XML To read and write data To read and write XMLSchema
.Common
Contains classes shared by both
Data Adapter
Loads a table from a data store and writes changes back.
Exposes two important methods:
Fill(DataSet,DataTable) Update(DataSet,DataTable)
Provides mappings between tables & columns User provides insert/update/delete commands
Allows use of Stored Procedures CommandBuilder component available (not used much in ASP.NET)
data store
DataAdapter
DataSet
Code: Insert/Update/Delete
String str = ""; OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=D:\\MCA\pro.mdb"); try { str="Insert into pro2(firstname,lastname) values(name1',name2')"; OleDbCommand cmd = new OleDbCommand(str,cn); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } catch (Exception e1) { } }
OleDbDataReader
Forward-only data access Lightweight programming model Less overhead than using OleDbDataAdapter Instantiated & returned by OleDbCommand.ExecuteReader Ties up the OleDbCommand until it is finished reading
OleDbDataReader
Properties of Interest: FieldCount: Returns the number of fields in the result set RecordsAffected: Number of affected records Methods to retrieve data: By column type and/or index: GetValue; GetString; etc. Read(): Advances reader to next record NextResult(): Advanced to next result set in batch GetValues(): Gets the current row
OleDbDataReader Sample
// Code for creating the OleDbConnection adoConn not shown String myQuery = SELECT * FROM Customers; adoConn.Open(); OleDbCommand myCmd = new OleDbCommand( myQuery,adoConn ); // Declare the OleDbDataReader & // then instantiate it with ExecuteReader(...) ... OleDbDataReader reader = myCmd.ExecuteReader(); // Always call Read before accessing data. while( reader.Read() ) { Object [] cols = new Object[10] ; reader.GetValues( cols ); Console.WriteLine( cols[0].ToString() + " | " + cols[1] ); } // Always Close the reader and the connection when done reader.Close(); adoConn.Close();
Cleanup
Close your connection objects and return them to the connection pool. Dispose all objects. Don't wait on the finalizer.
Summary
ADO.NET is
Optimized for Data Access.
Managed Providers for connected access DataSet for disconnected, user interaction DataReader for connected RO use.
Open Architecture
No Black Boxes
Tightly Integrated with XML