In this article we will see that how can use and execute the SQL Commands in Visual Studio. In this article we are using C# language. As we proceed in this article you will see that what steps are required to perform this task. We need the two main classes to do this. These classes are SqlConnection and SqlCommand. Â First we will use to include the namespaces that are required to using these two classes. First we will include two namespaces by using ‘using’ keyword. After importing this namespaces we will create the object for SqlConnection and SqlCommand.
The Namespaces that are required:
Now will study the procedure that we will be follow:-
Step 1:Â At first you need to create an object for sqlconnection class so that you can access the methods of this class. As we created the object ‘con’ of this class below:
SqlConnection con = new SqlConnection();
Step 2: After creating the object con of SqlConnection class we now need to assign the ConnectionString to this object. Without assigning the connection string we can not access the SQL Server Database. We assign the database connection string in double quotes.
con.ConnectionString = “Data Source=INDIA;Initial Catalog=DATABASE;Integrated Security=True“;
Step 3:Â Now we have to create the object of SqlCommand class so that the command can be used that are required.
SqlCommand cmd = new SqlCommand();
Step 4:Â After creating the object of SqlCommand Class we need to assign the CommandText value for the object. The CommandText may be the query or name of stored procedure that we want to execute.
Step 5: Now its turn to show whether we have put the query of storedprocedure in CommandText field. If we have uses the query then we have to show CommandType as Text otherwise we have to show the CommandType as StoredProcedure. If we not assign any value as CommandType then by default it takes as Text values;
cmd.CommandType = CommandType.StoredProcedure/ CommandType.Text;
Step 6: Then now we can open the connection to execute the command by using following statement.
Step 7: Now we can execute the SqlCommand methods according to our requirement.
Step 8: After executing the SqlCommand we need to close the connection for safety purpose.