5. SQLCommand ()
It is used to store and execute the SQL statement or Stored Procedure on a SQL Server database.
The SqlCommand class is a sealed class. it will provides the following five constructors.
public sealed class SqlCommand : DbCommand, ICloneable
1. public SqlCommand();
2. public SqlCommand(string cmdText);
3. public SqlCommand(string cmdText, SqlConnection connection);
4. public SqlCommand(string cmdText, SqlConnection connection, SqlTransaction transaction);
5. public SqlCommand(string cmdText, SqlConnection connection, SqlTransaction transaction, SqlCommandColumnEncryptionSetting columnEncryptionSetting):
Method
BeginExecuteNonQuery() It is used to Initiate the asynchronous execution of the SQL statement described by this SqlCommand.
Cancel() It tries to cancel the execution of a SqlCommand.
Clone() It creates a new SqlCommand object that is a copy of the current instance.
CreateParameter() It creates a new instance of a SqlParameter object.
ExecuteReader() It is used to send the CommandText to the Connection and builds a SqlDataReader.
ExecuteXmlReader() It is used to send the CommandText to the Connection and builds an XmlReader object.
ExecuteScalar() It executes the query and returns the first column of the first row in the result set. Additional columns or rows are ignored.
Prepare() It is used to create a prepared version of the command by using the instance of SQL Server.
ResetCommandTimeout() It is used to reset the CommandTimeout property to its default value.
<add name="DBConn" connectionString="Data Source=.;
Initial Catalog=fly; Integrated Security=True;Pooling=False"/>
</connectionStrings>
public class StudentDBHandle
{
private SqlConnection con;
private void connection()
{
string constring = ConfigurationManager.ConnectionStrings["DBConn"].ToString();
con = new SqlConnection(constring);
}
// **************** NEW STUDENT*********************
public void GetStudent()
{
try
{
connection();
SqlCommand cmd = new SqlCommand("select * from student", con); // Opening Connection
connection.Open();
// Executing the SQL query
SqlDataReader sdr = cm.ExecuteReader();
while (sdr.Read())
{
Console.WriteLine(sdr["Name"] + ", " + sdr["Email"] + ", " + sdr["Mobile"]);
}
}
catch (Exception e)
{
Console.WriteLine("OOPs, something went wrong.\n" + e);
}
}