SQL with CS

From SQLZOO
Revision as of 17:10, 13 April 2020 by Andr3w (talk | contribs) (Created page with "The namespace System.Data.SqlClient includes the SqlCommand class that has all you need to run SQL from C# using System; using System.Data.SqlClient; class Program { st...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

The namespace System.Data.SqlClient includes the SqlCommand class that has all you need to run SQL from C#

using System;
using System.Data.SqlClient;
class Program
{
  static void Main(string[] args)
  {
    SqlCommand command = new SqlCommand(
      "select capital from world where name=@name",
      new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=sqlzoo;Integrated Security=True"
    ));
    command.Parameters.Add(new SqlParameter("name", "France"));
    command.Connection.Open();
    SqlDataReader sdr = command.ExecuteReader();
    while (sdr.Read())
    {
      Console.WriteLine(sdr["capital"]);
    }
    command.Connection.Close();
  }
}