Previous | Home | Next |
When we have a more complex query that retrieves records from different tables, or don't wado.net the UPDATE command to check for changes in the database before updating it, we can specify our own SQL commands.The Command object enables to execute queries against data source. in order to retrieve data, you must know the schema of your database as well as how to build a valid SQL query. The Command objects allow developers to specify parameters dynamically at run time. When defining the SQL statement we use a placeholder instead of a particular value. Then we use the Parameters collection of the Command object to define the dynamic column value.The SqlCommand object must be used in conjunction with the SqlConnection object
Creating a SqlCommand Object
SqlCommand cmd = new SqlCommand("select CategoryName from Categories", new sqlconnection(parameter));
Querying Data
using a SQL select command
- Instado.netiate a new command with a query and connection
- Call Execute reader to get query results
SqlCommand cmd = new SqlCommand("select EmployeeName from Emp",conn);
SqlDataReader dr = cmd.ExecuteReader();
Inserting Data
using a SQL insert command,To insert data into a database, use the ExecuteNonQuery method of the SqlCommand object.
- Insert command string
- Instado.netiate a new command with a query and connection
- Call ExecuteNonQuery to send command
string insertString = @"insert into Emp(EmpName, Post)values ('Aditya', 'S\w Engg')";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.ExecuteNonQuery();
Updating Data
using a SQL update command,To update data into a database, use the ExecuteNonQuery method of the SqlCommand object.
- prepare command string
- Instado.netiate a new command with command text only
- Call ExecuteNonQuery to send command
string updateString = "update Emp set EmpName = 'Ashish' where CategoryName = 'Raj'";
SqlCommand cmd = new SqlCommand(updateString,conn);
cmd.ExecuteNonQuery();
Deleting Data
using a SQL delete command,To delete data into a database, use the ExecuteNonQuery method of the SqlCommand object.
- delete command string
- Instado.netiate a new command
- Set the CommandText property
- Set the Connection property
- Call ExecuteNonQuery to send command
string deleteString =" delete from Emp where EmpName = 'Ashish'";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = deleteString;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
Getting Single Values
For getting a single value we can use count, sum, average, or other aggregated value from a data set.
- Instado.netiate a new command
- Call ExecuteNonQuery to send command
SqlCommand cmd = new SqlCommand("select count(*) from Categories", conn);
int count = (int)cmd.ExecuteScalar();
Previous | Home | Next |