ADO. NET provides Connection to connect to the database and Command object to query the database. Like the Connection object, there are two types of commands: OleDbCommand and SqlCommand. The difference is the same as that of the Connection object.
To manipulate the database, you must first use Connection to connect to the database, and then create a Command to query. There are several creation methods, for example:
SqlCommand cmd;
String strCon = "server = localhost; database = Northwind; Trusted_Connection = Yes ;";
String strqry = "select * from Categories ";
SqlConnection con = new SqlConnection (strCon );
Con. Open ();
Cmdcmd = con. CreateCommand (); // use the CreateCommand method of the Connection object to create a Command object.
Cmd. CommandText = strqry;
// SqlDataReader reader = cmd. ExecuteReader ();
2. cmd = new SqlCommand (); // directly use the new keyword to create
Cmd. CommandText = strqry;
Cmd. Connection = con; // set the Connection to the database
Cmdcmd = new SqlCommand (strqry, con); // create a new SQL command with two parameters.
Execution method:
(There are several main types: cmd. ExecuteReader (); cmd. ExecuteNonQuery (); cmd. ExecuteScalar (); cmd. ExecuteXmlReader ();)
1. ExecuteReader (); returns a SqlDataReader object or OleDbDataReader object, which depends on your program. You can use this object to check the query results. It provides a "swimming" execution method, that is, after reading a row from the result and moving it to another row, the previous row cannot be reused. One thing to note is that after execution, the DataReader object will be moved to the first row of the result set after the Read () method is manually called, And a Bool value will be returned for this method, indicates whether the next row is available, True is available, and False is returned to the end of the result set.
DataReader can improve the execution efficiency. There are two ways to improve the Code Performance: one is serial number-based search, and the other is to use the appropriate Get Method for search. Because the query results are generally not changed, unless the query statement is modified again, you can locate the column to find the record. One problem with this method is that you may know the name of a column without knowing its location. The solution to this problem is to call the GetOrdinal () method of the DataReader object, this method receives a column name and returns the column number of the column name. Example:
Int id = reader. GetOrdinal ("CategoryName ");
While (reader. Read ())
{
Response. Write (reader [id]);
}
Reader. Close ();
The second method is intuitive, for example:
While (reader. Read ())
{
Response. Write (reader. GetInt32 (0). ToString () + "" + reader. GetString (1). ToString () + "<br> ");
}
GetInt32 () and GetString () of DataReader return the value of a column by receiving a column number. These two types are the most commonly used, and there are many other types.
(Note: The DataReader object closes the connection to the database by calling the Close () method. If the second connection is re-opened before it is closed, an exception message is generated)
2. ExecuteNonQuery () does not return a DataReader object, but returns an int value, that is, the number of rows affected by the execution in the database.
Example:
Int affectrows = cmd. ExecuteNonQuery ();
Response. Write (affectrows + "affected records ");
3. The ExecuteScalar () method does not accept any parameters. It only returns the first column of the First row in the query result set, ignoring other rows and columns, and returns an object type, before use, you must forcibly convert it to the required type. If only one data element is returned, you can use this method to improve the Code performance. Example:
String strCon = "server = localhost; database = Northwind; Trusted_Connection = Yes ;";
String strqry = "select count (*) from Categories ";
SqlConnection con = new SqlConnection (strCon );
Con. Open ();
SqlCommand cmd = con. CreateCommand ();
Int I = Convert. ToInt32 (cmd. ExecuteScalar (); // mandatory Conversion
4. ExecuteXmlReader () This method is used for XML operations and returns an XmlReader object. Because the System does not reference the System. Xml namespace by default, it must be introduced before use. Example:
String strCon = "server = localhost; database = Northwind; Trusted_Connection = Yes ;";
SqlConnection con = new SqlConnection (strCon );
Con. Open ();
SqlCommand cmd = new SqlCommand ("select * from Categories for xml auto, XMLDATA", con );
XmlReader xr = cmd. ExecuteXmlReader ();
Response. Write (xr. AttributeCount); // obtain the number of attributes on the current node.
Xr. Close ();
After the execution is complete, you must call the Close () method explicitly. Otherwise, an exception is thrown.
Use parameterized Query
First look at an SQL statement: select CategoryID, Description from Categories where CategoryID =? The question mark is a parameter. However, the name parameter with the @ prefix must be used, because the. NET data provider does not support this generic parameter mark "?". Using parameterized queries can greatly simplify programming, and the execution efficiency is higher than that of directly querying strings. In many cases, you need to change the query string. This method provides convenience, you only need to change the parameter value. Example:
String strCon = "server = localhost; database = Northwind; Trusted_Connection = Yes ;";
SqlConnection con = new SqlConnection (strCon );
Con. Open ();
String strqry = "select * from Categories where CategoryID = @ CategoryID"; // query with Parameters
SqlCommand cmd = new SqlCommand (strqry, con );
Cmd. Parameters. Add ("@ CategoryID", SqlDbType. Int, 4); // assign the parameter to the same type in the same database
Cmd. Parameters ["@ CategoryID"]. Value = "3"; // assign a Value to the parameter, which can be changed flexibly.
SqlDataReader r = cmd. ExecuteReader ();
While (r. Read ())
{
Response. Write (r. GetString (2) + "<br>"); // retrieves the value of the specified parameter Column
}
Con. Close (); // remember to Close