I. Basic Knowledge
When using ADO. NET to access data, there are two methods:
1. Use the Connection + Command + DataReader Method
You can use the Datareader object of ADO. NET to retrieve data from the database. The retrieved data formsRead-OnlyThe data stream is stored in the client's network buffer. The read method of the Datareader object can forward to the following record. By default, each read method is executed to store only one record in the memory, with very little overhead. Before creating a datareader, you must first create a sqlcommand object, and then call the executereader method of the object to construct the sqldatareader object, instead of directly using the constructor.
Example: ADO. NET -- Command (Execute SQL) & DataReader (read database)
2. Use Connection + DataAdapter + DataSet
This method mainly uses DataAdapter to serve as a bridge between DataSet and the data source for data retrieval and storage, and then stores the data retrieved from the database to DataSet or DataTable, that is, the local memory, and then the data is retrieved. In this way, the information in the database is copied on the local machine and a copy is generated. This copy is used, and the operation result is returned to the database. This saves network resources. However, in the case of concurrent operations by different users, PV operations may cause inaccurate user data due to time-related errors.
2. Example of database access using DataAdapter + DataSet instead of Comman + DataReader
Static void Main (string [] args) {// create a connection string strConn = "database = Login; server = localhost; UID = sa; PWD = 123456 "; // connection string using (SqlConnection conn = new SqlConnection (strConn) // establishes a connection and automatically closes {conn. open (); // Open the connection string strSQL = "select * from Users where ID = '1'"; // query statement SqlDataAdapter adapter = new SqlDataAdapter (strSQL, conn ); // execute the query DataSet dataset = new DataSet (); // The data adapter used to store the query. fill (dataset); // transfer the query result to dataset // display the query result DataTable table = dataset. tables [0]; // The first table int I = 0; // The first row = 0 DataRow row = table. rows [I]; // obtain the string name = Convert for each row. toString (row ["UserName"]); // converts the obtained object data to a string Console. writeLine ("ID is: 1; UserName is: {0}", name); // output ID = '1' corresponding UserName }}
Compared with read-only DataReader, you can use DataAdapter + DataSet to update the database.