We already know how to connect to the database. After opening the database, how can we operate the database? This requires the use of the command object, commandObjects can be added, deleted, modified, and queried on the database.
Like the connection object, the command object belongs to the. NET Framework dataProgramDifferent data providers have their own command objects. HereWe also discuss the command object based on SQL Server.
Main attributes and methods of the command object
Attribute
ConnectionDatabase connection used by the command object
CommandtextExecuted SQL statement
Method
Executenonquery ()Execute a statement that does not return rows, such as an update statement.
Executereader ()Run the query command to return the datareader object.
Executescalar ()Returns a single value, for example, execute count (*)
Here, we will focus on the executescalar () method of the command object. This method only returns the value of the first column in the first row of the query result.This method is usually used when the query result has only one value, for example, when an aggregate function is used. The Return Value of the method must be explicitly converted. BecauseThe returned value belongs to the object type.
To use the command object, you must have an available connection object. The steps for using the command object include:
1. Create a database connection
Create a connection object.
2. Define the executed SQL statement.
In general, the SQL statement to be executed is assigned to a string.
3. Create a command object
Use an existing connection object and SQL statement string to create a command object.
4. Execute SQL statements
Execute a command using a method of the command object.
Example:
Code:
-
- // The automatically generated reference namespace is omitted.
-
- UsingSystem. Data. sqlclient;
-
- NamespaceOpenclosedb
-
- {
-
- ClassDemo
-
- {
-
- Static VoidMain ()
- {
-
- StringConnstring ="Data Source =.; initial catalog = myschool; user id = sa; Pwd = 123456";
-
- Sqlconnection connection =NewSqlconnection (connstring );
-
-
- StringSQL =String. Format ("Select count (*) from student");
-
- Sqlcommand objcommand =NewSqlcommand (SQL, connection );
-
-
- Connection. open ();
-
- IntNumber = (Int) Objcommand. executescalar ();
-
-
- Connection. Close ();
-
- Console. writeline ("A total of {0} records", Number );
-
- }
-
- }
-
- }
Note: you must open the database before using the command object to execute commands.