System.Data.dll
.System.Data
namespace.System.Data.OleDb
namespace – A data provider used to access database such as Access, Oracle, or SQL.System.Data.SQLClient
namespace – Used to access SQL as the data provider.ADO | ADO.NET |
---|---|
ADO have recordset. | ADO.NET have data adopter and data set. |
The objects of ado communicate in binary mode. | It uses XML for passing the data. |
It supports mostly connection oriented models. | It works in disconnected manners. |
It derives information about data implicitly at runtime based on metadata, so it is a costly process. | It uses known metadata at design time, so it provides better runtime performance and more consistent runtime behavior. |
It allows only client-side cursors. | It supports both client side and server side cursors. |
using System;
using System.Data.SqlClient;
using System.Data;
namespace DataAdapterExample
{
public partial class DataAdapterDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection("data source=.; database=items; integrated security=SSPI"))
{
SqlDataAdapter da = new SqlDataAdapter("Select * from items", conn);
DataSet s = new DataSet();
da.Fill(s);
GridView1.DataSource = s;
GridView1.DataBind();
}
}
}
} ​
ADO.NET(Active Data Objects) | ASP.NET(Active Server Pages) |
---|---|
ADO.NET is a Library within the .NET framework. | ASP.NET is a Framework. |
It is a technology useful for accessing data from databases. | It is a technology useful for the creation of dynamic web pages. |
Here, data can be converted into XML format. | Here, We can write our code into VB.Net, C#, ASP.Net, etc. |
It is used to develop reliable and scalable database applications with high performance for client-server applications. | It is used to create dynamic web pages, web applications, websites, and web services. |
ADO.NET
. They are :.xsd file
) that contains DataSet structure information such as rows, columns, and tables. Data from the database is moved into a dataset and from the dataset to another component in the XML format.using System;
using System.Data.SqlClient;
using System.Data;
namespace DataSetDemo
{
public partial class DataSetExample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection("data source=.; database=employee; integrated security=SSPI"))
{
SqlDataAdapter da = new SqlDataAdapter("Select * from employee", conn);
DataSet d = new DataSet();
da.Fill(d);
GridView1.DataSource = d;
GridView1.DataBind();
}
}
}
}​
Here, DataSet will be filled by DataAdapter that receives data from the employee table. This DataSet will be used to display the information received from the employee database.
DataTable | DataSet |
---|---|
DataTable consists of a single database table that is placed within a memory. | DataSet consists of a collection of multiple database tables which is placed within a memory. |
It has a row and column collection. | It has a database table collection. |
It allows fetching only a single TableRow at a time. | It allows fetching multiple TableRows at a time. |
It is a single database table, so there will not be any relation with other tables. | It represents a collection of DataTable objects, so there might be a relation between them to obtain a particular result. |
In this, DataSource objects are not serialized. | In this, DataSource objects are serialized. |
UniqueConstraint and ForeignKeyConstraint objects are not available enforcing data integrity. | UniqueConstraint and ForeignKeyConstraint objects are available for enforcing data integrity. |
.aspx.cs
code,protected void BinddataTable()
{
SqlConnection con = new SqlConnection("your database connection string");
con.Open();
SqlCommand cmd = new SqlCommand("Write your query or procedure", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
grid.DataSource = dt;
grid.DataBind();
}
// Create a command builder object
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
DataView custDV = new DataView(customerDS.Tables["Customers"],
"Country = 'USA'",
"ContactName",
DataViewRowState.CurrentRows);
DataView custDV = customerDS.Tables["Customers"].DefaultView;
private void frmSqlCommand_Load(object sender, EventArgs e)
{
//Sample 03: Open Database Connection
String con_string = Properties.Settings.Default.ConStrPubs;
pubs_db_connection = new SqlConnection(con_string);
pubs_db_connection.Open();
//Sample 04: Form the Command Object
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select Count(*) as Count from Titles";
cmd.Connection = pubs_db_connection;
//Sample 05: Execute the Command & retrive scalar value
lblTotal.Text = System.Convert.ToString(cmd.ExecuteScalar());
}
SqlDataAdapter da;
DataSet ds;
string strconn = "Data Source=YourServerName;Initial Catalog=EMP;Integrated Security=True";
private void Form1_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter("select * from userdet", strconn);
ds = new System.Data.DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
execute()
methods supported by SqlCommandObject in ADO.NET
is given below :ExecuteReader()
method.public void CallExecuteNonQuery()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
try
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "DELETE FROM EMP WHERE DEPTNO = 40";
cmd.CommandType = CommandType.Text;
conn.Open();
Int32 RowsAffected = cmd.ExecuteNonQuery();
MessageBox.Show(RowsAffected + " rows affected", "Message");
cmd.Dispose();
conn.Dispose();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
DataRelation drel;
drel = new DataRelation("All", ds.Tables[0].Columns[0], ds.Tables[1].Columns[0]);
OLEDB
provider is used to access any database and provides flexibility of changing the database at any time. SQLClient
provider is used to access only SQL Server
database but it provides excellent performance than OLEDB
provider while connecting with SQL Server database
. OLEDB | ODBC |
An API (Application Programming Interface) enables standard data access from many sources. | It's a database management system interface (DataBase Management System). |
Both relational and non-relational databases can be used with it. | It only works with databases that are relational. |
It follows a set of steps. | It's built on the concept of components. |
It's a lot more straightforward to use. | It's a challenge to put into action. |
It improves the loading and extraction of data performance. | In terms of data loading and extraction, it performs worse than OLE DB. |
To connect to an OLE DB data source, use OleDbConnection = New OleDbConnection(connectionString). | To connect to an ODBC data source, use the resource ODBC connect(string data source, string username, string password, [int cursor type]). If this method succeeds, it will return a connection resource handle that may be used to access the database with the following instructions. |
SqlTransaction
class is an important class of .NET Framework. It ensures that a body of code will affect a Database or kept the same as previous (Rollback).XmlReader xmlreader = cmd.ExecuteXmlReader();
XmlDocument xdoc = new XmlDocument();
ExecuteScalar()
method on query execution.COUNT(), SUM(),
etc., as it uses only a few resources compared to the ExecuteReader()
method.public void ExecuteScalarExample()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
try
{
SqlCommand cd = new SqlCommand();
cd.Connection = con;
cd.CommandText = "SELECT SUM(SALARY) FROM EMPLOYEE";
cd.CommandType = CommandType.Text;
con.Open();
Int32 SalaryTotal = Convert.ToInt32(cd.ExecuteScalar());
MessageBox.Show("Total Salary of the employee is : " + SalaryTotal.ToString());
cd.Dispose();
con.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}​
ExecuteScalar()
function gets executed, a single value will be returned, i.e, the total salary of employees. This value will be displayed using a message box.SqlConnection.ConnectionString
specifies Windows authentication without any need of providing a user name or password by the user."Server=MSSQL1;Database=Institute;Integrated Security=true;​
"Persist Security Info=False;User ID=Harsh;Password=xyz@123;Initial Catalog=Institute;Server=MySqlServer"
Response.Expires
property is specific to the minutes that a particular page stays in the cache for the specific time from the time it has been requested. For example, if Response.Expires
value is set to 5 minutes, then the page is instructed to be in cache for 5 minutes from the time it has been requested.Response.ExpiresAbsolute
property helps to provide the proper time at which a specific page cache has been expired. For example, Response.ExpiresAbsolute
provides information like 14 March 15:40:15. This time tells about when the page was in cache.AcceptChanges()
method.RejectChanges()
method, if you want to reverse the entire changes since from the time the DataSet object was loaded.using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml.Serialization;
using System.IO;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=data_source_name;Initial Catalog=employee;Integrated Security=True"); //Create connection object
SqlDataAdapter da = new SqlDataAdapter("select * from emp", conn); //DataAdapter creation
DataSet s = new DataSet();
da.Fill(s);
FileStream fObj = new FileStream("C:\\demo.xml", FileMode.Create); // Create a XML file
XmlSerializer sObj = new XmlSerializer(typeof(DataSet));
sObj.Serialize(fObj, s); //Serialization of a DataSet
fObj.Close();
}
}
Serialize()
method.AddNew(
), MoveFirst( )
, MovePrevious( )
, MoveNext( )
, etc which provide easier way for adding new row, moving to first record, moving to previous record, moving to next record and many other operations without writing code for them.