Skip to content

SQL C#

C# SQL
Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!

In this article you will learn how to use SQL in C#.

You can use sql in c# by using the System.Data.SqlClient namespace. This namespace provides data access for Microsoft SQL Server.

Here is a program which explains everything in a practical approach:

using System;
using System.Data.SqlClient;

class Program {
  static void Main(string[] args) {
    // This program uses a simple SQL database to store information about films.
    // The user can add new books to the database, or query the database for
    // information about a specific film.

    // First, we need to connect to the database. We do this using a
    // SqlConnection object. We need to specify the database server and the
    // name of the database.
    SqlConnection connection = new SqlConnection(
        "Server=localhost;Database=Films;Trusted_Connection=True;");

    // We can open the connection using the Open() method.
    connection.Open();

    // Now that we have a connection, we can execute SQL commands.
    // We do this using a SqlCommand object. We need to specify the SQL
    // command, as well as the connection object.
    SqlCommand command = new SqlCommand("SELECT * FROM Films", connection);

    // We can execute the SQL command and get the results back in the form
    // of a SqlDataReader object.
    SqlDataReader reader = command.ExecuteReader();

    // We can use the SqlDataReader object to read the results of the query.
    // For example, we can use the Read() method to read each row of the
    // results.
    while (reader.Read()) {
      // We can get the values of each column using the indexer.
      // For example, the Title column is at index 0.
      string title = reader [0].ToString();
      string studio = reader [1].ToString();
      int year = (int) reader[2];

      Console.WriteLine("Title: {0}, Studio: {1}, Year: {2}", title, studio,
                        year);
    }

    // We need to close the connection when we're done.
    connection.Close();
  }
}

We hope that this simple program helped you understanding how you can use SQL in C#.

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!
Tired of being just an average developer?
Stop wasting your time and learn coding the right (and easy) way!
Tired of being just an average developer?
Stop wasting your time and learn coding the right (and easy) way!
Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide