ADO. NET (Data Access Technology) and ado.net access
To put it simply, C # has built-in classes that we can use to access the database. Here, we assume that the reader is familiar with SqlServer database or other databases (I will also add relevant content later ). How can we implement this technology? There are roughly three steps: 1. Connect to the database 2. Set the operation/command 3. execute the operation. The statement is as follows:
1. to connect a database to a database, we need to use a database connection class SqlConnection. To use this class, we must first use the namespace (using System. data. sqlClient;) or right-click the class name and select reference. The Code is as follows:
SqlConnection conn = new SqlConnection ("server = ..; database = FirstDB; user = sa; pwd = 123 ");
The server here is the server, "." indicates the local server, and other servers can use the ip address. Database is the database you want to use on this server. User and pwd are the usernames and passwords you want to use to log on to the server.
2. Set the operation/command code as follows:
// Create a command class
SqlCommand cmd = conn. CreateCommand ();
// Set SQL statements
Cmd. CommandText = "delete from Employee ";
3. perform the operation
// Enable the database Channel
Conn. Open ();
// Execute
Cmd. ExecuteNonQuery ();
// Closes the database Channel
Conn. Close ();
It is worth noting that the above methods are basically applicable to the addition, deletion, and modification operations. The difference is the content of SQL statements. However, for queries, we must not only change the SQL statement, but also modify the execution operations. The Code is as follows:
3. perform the operation
Conn. Open ();
// Read data
SqlDataReader dr = cmd. ExecuteReader ();
// Read the next record (each time this method is executed, the next record will be read and stored in the dr collection)
Dr. read ();
// We will print this record here (assuming there are only two data records in this record)
Console. writeLine (dr [0] + "\ t" + dr [1])
// Closes the database Channel
Conn. Close ();