methods of the sql command class
DESCRIPTION
SQL Command Class ASP.NETTRANSCRIPT
Database Connections
The SqlConnection object used in ASP.NET applications is constructed using a connection string. These can be hard coded into an ASP.NET page but are much more efficiently stored in the Web.Config file.
Eg In the diagram below the connection string is stored with the name ApplicationServices. It is possible to store many connection strings in the Web.Config file but you will normally only use one database.
Retrive the Connection String in the Code
string conString = Configuration.Manager.ConnectionStrings(AdvWorks).ConnectionString;
SqlConnection sqlConn = new SqlConnection(conString);
sqlConn.Open();
Methods of the SQL Command Class
ExecuteNonQuery
1. ExecuteNonQuery is used to execute a SQL statement or stored procedure that doesnt return any records. Youll use this method when executing operations that update, insert, or delete information in the database.
2. ExecuteNonQuery returns an integer value that specifies how many rows were affected by the querythis proves useful if you want to know, for example, how many rows were deleted by the last delete operation
Example Usage
The lines that follow show how to open the connection, execute the command using ExecuteNonQuery, and close the connection after execution.
connection.Open();
command.ExecuteNonQuery();
command.Close();
ExecuteScalar
ExecuteScalar is like ExecuteNonQuery in that it returns a single value, although it returns a value that has been read from the database instead of the number of affected rows.
It is used in conjunction with SELECT statements that select a single value. If SELECT returns more rows and/or more columns, only the first column in the first row is returned.
A typical SQL query that should be executed using ExecuteScalar is SELECT COUNT(*) FROM Departmentwhich returns the
number of rows in the Department table.
ExecuteReader
ExecuteReader is used with SELECT statements that return multiple records (with any number of fields). ExecuteReader returns a SqlDataReader object, which contains the results of
the query. A SqlDataReader object reads and returns the results one by one, in a forward-only and read-only manner.
The SqlDataReader is that it represents the fastest
way to read data from the database but it needs an open connection tooperateno other database operations can be performed on that connection until the reader is closed.
You can load all the data returned by the SqlDataReader into a DataTable object (which is capable of storing the data offline without needing an open connection), which will allow you to close the database connection very quickly.
The DataTable class can store a result set locally without needing an open connection to SQL Server.
You can also load the results of a reader into a DataSet which is an object that represents an in-memory database. DataSet is capable of storing data tables, their data types, relationships between tables, and so on. Because of their complexity, DataSets consume a lot of memory, so its good to avoid them when possible.
Heres a simple example of reading some records from the database and saving them to a DataTable:
// Open the connection
conn.Open();
// Create the SqlDataReader object by executing the command
SqlDataReader reader = comm.ExecuteReader();
// Create a new DataTable and populate it from the SqlDataReader
DataTable table = new DataTable();
table.Load(reader);
// Close the reader and the connection
reader.Close();
conn.Close();
Stored procedures
Stored procedures are database objects that store programs written in T-SQL. Much likenormal functions, stored procedures accept input and output parameters and have return values.can directly send the SQL commands from an external application to SQL Server. When using stored procedures, instead of passing the SQL code you want executed, you just pass the name of the stored procedure and the values for any parameters it might have. Using stored proceduresfor data operations has the following advantages
better performance
better security
easier maintenance
prevents injection attacks
Creating a Stored Procedure
CREATE PROCEDURE
AS
Example
CREATE PROCEDURE GetDepartments AS
SELECT DepartmentID, Name, Description
FROM Department
// Create the command object
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "CatalogGetDepartments";
command.CommandType = CommandType.StoredProcedure;
Stored Procedures with Parameters
CREATE PROCEDURE
[(
[=] [INPUT|OUTPUT],
[=] [INPUT|OUTPUT],
...
...
)]
AS
Example
CREATE PROCEDURE CatalogGetDepartmentDetails
(@DepartmentID INT)
AS
SELECT Name, Description
FROM Department
WHERE DepartmentID = @DepartmentID
www
Exception Handling
try
{
// code that might generate an exception
}
catch (Exception ex)
{
// code that is executed only in case of an exception
try
{
// Open the data connection
command.Connection.Open();
// Execute the command and save the results in a DataTable
DbDataReader reader = command.ExecuteReader();
table = new DataTable();
table.Load(reader);
// Close the reader
reader.Close();
}
catch (Exception ex)
{
Utilities.LogError(ex);
throw;
}
finally
{
// Close the connection
command.Connection.Close();
}
return table;
}