A Closer Look at ADO.NET: The Command Object (Page 1 of 5 )
In this article, Michael Youssef shows us how to use the Command Object to execute SQL commands on the database server. He details commands we need to perform on the database like INSERT, UPDATE, DELETE and SELECT, represented in ADO.NET as Command Object. You should already know how to create a connection with the database, or you can refer to "A Closer Look at ADO.NET: The Connection Object" to learn how.
As with the connection object, there are provider-specific classes for the command object. For example, the SQL Server Provider has the class SqlCommand and the OLEDB .NET Data Provider has the class OleDbCommand. The Command Classes implement the IDbCommand Interface, which has methods like ExecuteReader(), ExecuteNonQuery(), ExecuteScalar(), CreateParameter(), Cancel() and Prepare(). The interface also has the following properties: Connection, CommandTimeout, CommandType, CommandText, Parameters and Transaction. We will be discussing all these properties and methods, so don't worry about that.
You can create a command object in many ways. You can create a connection object, then use the method CreateCommand() of the connection object to create a Command Object. Or you can create a connection object, then create a command object using the new operator (the standard way). After that, assign the connection object reference to the Connection property of the command object.
The command object has a property called CommandText, which contains a string value that represents the command that will be executed in the database server. So to use the command object, you must associate it with a connection object (which must be open before you use the command Object). Then assign the command string value to the CommandText property and use of the Execute methods.
The CommandType property takes a value of the System.Data.CommandType Enumeration (CommandType.Text, CommandType.TableDirect or CommandType.StoredProcedure). ADO.NET recognizes three types of commands. The first type is text commands, which are those text commands that are sent to the database server directly and written in specific SQL Dialect (for SQL Server, MSDE and Access it's T-SQL). The commandType.Text is the default for the property CommandType of the Command object.
The second type is the CommandType.StoredProcedure which is set to call a specific stored procedure in the database; of course when you set the Command.CommandType property to CommandType.StoredProcedure, the value of the Command.CommandText must be the name of the stored procedure that you are calling. Finally, the type CommandType.TableDirect is used to return a complete table from the database, and it's used only by the OLEDB .NET Data Provider. I think that it's time to create a command object and execute a T-SQL Command in the database.
Next: The ExecuteScalar() Method >>
More Database Code Articles
More By Michael Youssef