1 Overview
ado.net provides a rich database operations, these operations can be divided into three steps:
- First, using SqlConnection object database connection;
- Second, to establish the SqlCommand object, and call stored procedures responsible for the implementation of SQL statements;
- Third, the SQL or stored procedure returns execution after "result" of operation.
To return to the "Results" operations can be divided into two categories:
- First, by using the direct line by line SqlDataReader read data set;
- Second, the United DataSet SqlDataAdapter to operate the database.
Both comparison:
- SqlDataReader in time with the remote database connected to the server, the remote data forms "flow" of the one-way transmission to the client, it is "read-only". Because it is direct access to the database, it is more efficient, but not convenient to use.
- DataSet disposable acquired from the data source to the local data, and create a mini-database (comprising tables, rows, columns, the relationship between the rules, tables, etc.) locally, may be disconnected during the connection to the server, using the operation SqlDataAdapter object " local mini-database ", after the one-time update to a remote database server by SqlDataAdapter. This approach uses up more square, it is simple. But a little bit worse performance than the first. (In the general case of both properties is negligible.)
A very well-known ADO.NET architecture diagram:
2, the connection string wording
string connectString = "Data Source=.;Initial Catalog=Student;Integrated Security=True";
3, SqlConnection Object
Namespace: System.Data.SqlClient.SqlConnection;
Returns database connection object, parameter string. Examples of "connection object", and opens the connection
SqlConnection sqlCnt = new SqlConnection(connectString); sqlCnt.Open();
After completion of use, and needs to close "connection object"
sqlCnt.Close();
4, SqlCommand Object
Namespace: System.Data.SqlClient.SqlCommand;
SqlCommand object for performing database operations, the operation in three ways:
- SQL语句:command.CommandType = CommandType.Text;
- Stored procedure: command.CommandType = CommandType.StoredProcedure;
- Entire table: command.CommandType = CommandType.TableDirect;
Examples of a SqlCommand object
SqlCommand command = new SqlCommand(); command.Connection = sqlCnt; // 绑定SqlConnection对象
Or created directly from SqlConnection
SqlCommand command = sqlCnt.CreateCommand();
Common methods:
- command.ExecuteNonQuery (): returns the affected function, such as add, delete, change operation;
- command.ExecuteScalar (): execute the query and returns the results of the first line of the first column;
- command.ExecuteReader (): returns a data stream (the SqlDataReader object).
Common Operations
① execute SQL
SqlCommand cmd = conn.CreateCommand (); // create a SqlCommand object cmd.CommandType = CommandType.Text; cmd.CommandText = "from the SELECT * Products's @ID ="; // SQL statement cmd.Parameters.Add ( "@ ID" , SqlDbType.Int); . cmd.Parameters [ "@ ID"] = the Value. 1; // parameters sql statement to assign
② call a stored procedure
Cmd = conn.CreateCommand the SqlCommand (); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandText = "stored procedure name";
③ the entire table
SqlCommand cmd = conn.CreateCommand(); cmd.CommandType = System.Data.CommandType.TableDirect; cmd.CommandText = "表名"
5, SqlDataReader Object
Namespace: System.Data.SqlClient.SqlDataReader;
SqlDataReader object function provides read-only unidirectional data unidirectional: only data sequentially read next; read-only: the DataReader data is read-only, can not be modified; data corresponding to DataSet can read and modify any .
It has a very important method is the Read (), the return value is a Boolean value, is to advance to the next data, a section of the return data is executed, when the jump is false boolean value is true. Such as
= New new of the SqlCommand the Command of the SqlCommand (); command.Connection = sqlCnt; command.CommandType = CommandType.Text; command.CommandText = "* from the Select the Users"; SqlDataReader = Command.ExecuteReader Reader (); // execute SQL, returns a " stream " the while (reader.Read ()) { Console.Write (Reader [" username "]); // print out each user's user name }
6, DataSet objects
6.1 SqlDataAdapter;
Namespace: System.Data.SqlClient.SqlDataAdapter;
Is a bridge between SqlCommand SqlDataAdapter and DataSet, SqlDataAdapter object instantiated:
SqlConnection sqlCnt = new SqlConnection(connectString); sqlCnt.Open(); // 创建SqlCommand SqlCommand mySqlCommand = new SqlCommand(); mySqlCommand.CommandType = CommandType.Text; mySqlCommand.CommandText = "select * from product"; mySqlCommand.Connection = sqlCnt; // 创建SqlDataAdapter SqlDataAdapter myDataAdapter = new SqlDataAdapter(); myDataAdapter.SelectCommand = mySqlCommand; // 为SqlDataAdapter对象绑定所要执行的SqlCommand对象
SQL can be simplified as above
The SqlConnection = new new sqlCnt the SqlConnection (connectString); sqlCnt.Open (); // hide the definition SqlCommand objects while hiding bound SqlCommand object and SqlDataAdapter object SqlDataAdapter myDataAdapter = new SqlDataAdapter ( "select * from product", sqlCnt) ;
Properties and Methods
- myDataAdapter.SelectCommand properties: SqlCommand variable package Select statement;
- myDataAdapter.InsertCommand properties: SqlCommand variable package Insert statement;
- myDataAdapter.UpdateCommand properties: SqlCommand variable package Update statement;
- myDataAdapter.DeleteCommand properties: SqlCommand variable package Delete statements.
- myDataAdapter.fill (): The execution results are filled in the Dataset, hides open SqlConnection and perform SQL operations.
6.2 SqlCommandBuilder;
Namespace: System.Data.SqlClient.SqlCommandBuilder.
The operation of the DataSet (change, add, delete) only in local modifications, to submit to the "database" is required SqlCommandBuilder object. After the client for editing the data, the overall update data. Specific usage is as follows:
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder (myDataAdapter) ; // function to myDataAdapter given SqlCommandBuilder myDataAdapter.Update (myDataSet, "table"); // DataSet submitted after the changes to the database, the second parameter is the name of a stored table in the DataSet, not a real database table names (both the same in most cases).
6.3 DataSet
Namespace: System.Data.DataSet.
Data collection, local micro database can store multiple tables.
The first step is to use DataSet SqlDataAdapter return data sets (Tables) filled Dataset object:
= New new myDataAdapter the SqlDataAdapter the SqlDataAdapter ( "SELECT * from Product", sqlCnt); the DataSet myDataSet the DataSet new new = (); // Create the DataSet myDataAdapter.Fill (myDataSet, "Product"); // returns the data set as a "table" fill the DataSet, database table names may be different from the real table does not affect the subsequent add, delete, change operations and the like
① access data in the DataSet
SqlDataAdapter myDataAdapter = new SqlDataAdapter("select * from product", sqlCnt); DataSet myDataSet = new DataSet(); myDataAdapter.Fill(myDataSet, "product"); DataTable myTable = myDataSet.Tables["product"]; foreach (DataRow myRow in myTable.Rows) { foreach (DataColumn myColumn in myTable.Columns) { Console.WriteLine(myRow[myColumn]); //遍历表中的每个单元格 } }
② modify data in the DataSet
SqlDataAdapter myDataAdapter = new SqlDataAdapter("select * from product", sqlCnt); DataSet myDataSet = new DataSet(); myDataAdapter.Fill(myDataSet, "product"); // 修改DataSet DataTable myTable = myDataSet.Tables["product"]; foreach (DataRow myRow in myTable.Rows) { myRow["name"] = myRow["name"] + "商品"; } // 将DataSet的修改提交至“数据库” SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(myDataAdapter); myDataAdapter.Update(myDataSet, "product");
Note:. "For does not return any key column information SelectCommand, UpdateCommand does not support dynamic SQL generation" must be defined in a primary key modify, and delete tables product, select the field must also contain a primary key, otherwise it will prompt an error
③ add a line
= New new myDataAdapter the SqlDataAdapter the SqlDataAdapter ( "SELECT * from Product", sqlCnt); the DataSet myDataSet the DataSet new new = (); myDataAdapter.Fill (myDataSet, "Product"); the DataTable myTable myDataSet.Tables = [ "Product"]; // Add line the DataRow myRow myTable.NewRow = (); myRow [ "name"] = "Giant"; myRow [ ". price"] = 13.2; // myRow [ "ID"] = 100; if the ID is "Auto growth", this at may not be provided, even if the setting is also invalid myTable.Rows.Add (myRow); // modified DataSet submitted to "database" the SqlCommandBuilder MySqlCommandBuilder the SqlCommandBuilder new new = (myDataAdapter); myDataAdapter.Update (myDataSet, "Product");
④ delete a row
SqlDataAdapter myDataAdapter = new SqlDataAdapter("select * from product", sqlCnt); DataSet myDataSet = new DataSet(); myDataAdapter.Fill(myDataSet, "product"); // 删除第一行 DataTable myTable = myDataSet.Tables["product"]; myTable.Rows[0].Delete(); SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(myDataAdapter); myDataAdapter.Update(myDataSet, "product");
Attributes
- Tables: obtaining a set of tables contained in the DataSet.
- Relations: get used to link the table and allows you to browse the collection from the parent table to the child table relationships.
- HasEroors: Indicates whether the value has been initialized DataSet object.
method
- Clear Clear all DataSet object data for all tables.
- Clone DataSet object copied to another structure DataSet object, the copy includes all structures, relationships and constraints, but does not contain any data.
- Copy The data structures and objects to another DataSet DataSet object. Exactly the same two DataSet objects.
- CreateDataReader DataTableReader returns with a result set for each DataTable object, the display order of the same order Tables collection of tables.
- Dispose Releases resources DataSet object occupies.
- Reset will initialize the DataSet object.
7, free up resources
After use of resources should be released promptly and close the connection, as follows:
myDataSet.Dispose (); // release DataSet object myDataAdapter.Dispose (); // release SqlDataAdapter object myDataReader.Dispose (); // release the SqlDataReader sqlCnt.Close (); // close the connection sqlCnt.Dispose (); // release the database connection object
DataTable Detailed
summary:
after 1, delete () before receiving the AcceptChanges (), only marked for deletion, after once again accepted the AcceptChanges () before actually deleting, or did not receive AcceptChanges again () in case to RejectChanges () can be rolled back
2, delete () is not received before AcceptChanges (), immediately after receiving AcceptChanges (), also really delete
3, delete () is not received before AcceptChanges (), then did not immediately accept the AcceptChanges (), It will be completely removed: because there is no need to roll back
Add Reference
using System.Data;
Create a table
// create an empty table DataTable dt = new new DataTable (); // create a file called "Table_New" empty table DataTable dt = new DataTable ( "Table_New ");
Create a column
// Create an empty column the DataColumn the DataColumn new new DC = (); dt.Columns.Add (DC); // Create column with 2 column name and type name (one of two ways) dt.Columns.Add ( "column0", System.Type.GetType ( "System.String")); dt.Columns.Add ( "column0", typeof (String)); . // 3 by adding columns architecture column DataColumn dc = new DataColumn ( "column1", System.Type.GetType ( "System.DateTime")); the DataColumn the DataColumn new new DC = ( "column1", typeof (the DateTime)); dt.Columns.Add (DC);
Create a row
// Create an empty line. The DataRow dt.NewRow DR = (); dt.Rows.Add (DR); // create a blank line 2. Dt.Rows.Add (); .. 3 // created and assigned by a frame line dt.Rows.Add ( "Joe Smith", DateTime.Now); // Add the data sequence to which parameters and order of the columns corresponding dt
. @ 4 is created by copying a row dt2 table
dt.Rows. Add (dt2.Rows [i] .ItemArray) ;
Assignment and values
// Assignment new row the DataRow dt.NewRow DR = (); DR [0] = "John Doe"; // index assigned by dr [ "column1"] = DateTime.Now ; // name assigned by @ table existing line assignment dt.Rows [0] [0] = " John Doe"; // index by assigning dt.Rows [0] [ "column1" ] = DateTime.Now; // assignment by name // value name = dt.Rows String [0] [0] .ToString (); String = dt.Rows Time [0] [ "column1"] the ToString ().;
Line Screening
// column1 column select line set is empty the DataRow [] = dt.Select DRS ( "null column1 IS"); // set of rows selected column0 columns is "John Doe" in DataRow [] drs = dt. Select ( "column0 = 'John Doe'"); // filter has a set of column values column0 rows "sheet" (the fuzzy inquiry) the DataRow [] = dt.Select DRS ( "column0 like 'Double%'"); // If multiple filter conditions, and can add or or // column0 filter press set a value in the column column1 rows "sheets" in descending order DataRow [] drs = dt.Select ( " column0 like ' Double%'" , "column1 DESC");
Delete Row
// Use DataTable.Rows.Remove (DataRow) Method dt.Rows.Remove (dt.Rows [0]); // Use DataTable.Rows.RemoveAt (index) method dt.Rows.RemoveAt (0); // Use DataRow.Delete () method dt.Row [0] .Delete (); dt.AcceptChanges (); // ----- noted point and the difference ----- // the Remove () and RemoveAt () method delete // delete () method is just the line marked as deleted, but there are also DataTable.RejectChanges () rollback, so that the line to cancel. // When used Rows.Count to get the number of rows, or the number of rows before deleting, use DataTable.AcceptChanges () method to commit the changes. // If you want to delete multiple rows in the DataTable, should be used reverse circulation DataTable.Rows, circulation and can not be deleted with foreach, because the index will change when the positive sequence deleted, the occurrence of abnormal program, is difficult to predict the consequences. for (int I = dt.Rows.Count -. 1; I> = 0; i--) { dt.Rows.RemoveAt (I); }
Copy the table
// copy table, and copy the structure of the table and the table of the DataTable dtNew the DataTable new new = (); dtNew dt.Copy = (); // copy table DataTable dtNew = dt.Copy (); // copy data table dt structure dtNew.Clear () // clears the data for (int I = 0; I <dt.Rows.Count; I ++) { IF (condition statement) { dtNew.Rows.Add (dt.Rows [I] .ItemArray); // add rows } } // clone table, just copied table structure, does not include data DataTable dtNew = new new DataTable (); dtNew dt.Clone = (); // If only one row of a table DataTable = the DataTable new new dtNew (); dtNew dt.Copy = (); dtNew.Rows.Clear (); // Clear the data table the first row is // this is added; dtNew.ImportRow (dt.Rows [0])
Sorting table
DataTable dt = new DataTable (); // Create a table dt.Columns.Add ( "ID", typeof ( Int32)); // add columns dt.Columns.Add ( "the Name", typeof (String)); dt. Columns.Add ( "Age", typeof (Int32)); dt.Rows.Add (new object [] {. 1, "San", 20}); // add a row dt.Rows.Add (new object [] {2, "John Doe", 25}); dt.Rows.Add (new new Object [] {. 3, "Wang Wu", 30}); the DataView DV = dt.DefaultView; // Get the table view dv.Sort = "ID DESC"; // reverse order according ID dv.ToTable (); // table into