SqlDataReader and SqlDataAdapter differences
One, SqlDataReader//connection-based, read-only access suitable for smaller data volumes.
SqlDataAdapter//Based on non-connected, suitable for large data volume, can be modified, and finally return the results of the changes to the database. Ask for a bigger resource, too.
Second, SqlDataAdapter the data set into a dataset after reading the data, and the dataset's data exists in local customer service machine memory.
Third, SqlDataReader returned is a data reader, only one of the reading, operation is not flexible, generally in read-only time to use.
SqlDataAdapter returns a dataset or table that can manipulate the data in it.
Four, the different wording:
Sqldatreader the database must be opened before execution, and a command object must be generated. The value is then assigned by the Command.ExecuteReader () method. You must close the join manually after completion.
SqlCommand cmd = new SqlCommand ("SELECT * from Stu", Conn);
Conn. Open ();
SqlDataReader rdr = cmd. ExecuteReader ();
。。。。。
Conn.close ();
When SqlDataAdapter executes, the database is automatically opened and assigned without the command's ExecuteReader method, and the join is automatically disconnected when completed.
SqlDataAdapter adptr = new SqlDataAdapter (SQL, conn);
DataSet ds = new DataSet ();
Adptr. Fill (ds, "Stu");
Instance:
1, using SqlDataReader to read data
Class DataReader
{
static void Main ()
{
String str = "Server=localhost;uid=sa;pwd=123;database=northwind";
SqlConnection conn = new SqlConnection (str);
SqlCommand cmd = new SqlCommand ("SELECT * from Stu", Conn);
Conn. Open ();
SqlDataReader rdr = cmd. ExecuteReader ();
DataTable table=new datable ();
Table. Load (RDR);
Rdr. Close ();
Conn. Close ();
}
2, use SqlDataAdapter +dataset to read the modified data
Class SqlDataAdapter
{
static void Main ()
{
String str = "Server=localhost;uid=sa;pwd=123;database=northwind";
SqlConnection conn = new SqlConnection (str);
String sql = "SELECT * from Stu";
SqlDataAdapter adptr = new SqlDataAdapter (SQL, conn);//adepter Object
DataSet ds = new DataSet ();//dataset Object
Adptr. Fill (ds, "Stu");//populate the dataset and name the current table
DataTableReader rdr = ds. CreateDataReader ();
while (RDR. Read ())//reading data from table
{
for (int i = 0; i < RDR. FieldCount; i++)
{
Console.Write (RDR. GetName (i) + "\ T" + rdr. GetValue (i) + "\ T");
}
Console.WriteLine ();
}
}
SqlDataReader and SqlDataAdapter differences