C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ADO.NET SqlCommand ClassThis class is used to store and execute SQL statement for SQL Server database. It is a sealed class so that cannot be inherited. SqlCommand Signature
public sealed class SqlCommand : System.Data.Common.DbCommand, ICloneable, IDisposable ConstructorsThis class provides the following constructors.
Methods
Example
In this example, we are creating a SqlCommand instance and executing a SQL statement. // Program.cs
using System;
using System.Data.SqlClient;
namespace AdoNetConsoleApplication
{
class Program
{
static void Main(string[] args)
{
new Program().CreateTable();
}
public void CreateTable()
{
SqlConnection con = null;
try
{
// Creating Connection
con = new SqlConnection("data source=.; database=student; integrated security=SSPI");
// writing sql query
SqlCommand cm = new SqlCommand("select * from student", con);
// Opening Connection
con.Open();
// Executing the SQL query
SqlDataReader sdr = cm.ExecuteReader();
while (sdr.Read())
{
Console.WriteLine(sdr["name"]+" "+ sdr["email"]);
}
}
catch (Exception e)
{
Console.WriteLine("OOPs, something went wrong." + e);
}
// Closing the connection
finally
{
con.Close();
}
}
}
}
Output: Execute this program by combination of Ctrl+F5 and it will produce the following output.
It prints name and email of the student.
Next TopicADO.NET DataReader
|