Execute select query from code behind

13,954

Something like this:

 string queryString = 
    "SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
           connectionString))
{
    SqlCommand command = new SqlCommand(
        queryString, connection);
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    try
    {
        while (reader.Read())
        {
            Console.WriteLine(String.Format("{0}, {1}",
                reader["OrderID"], reader["CustomerID"]));
        }
    }
}

Source: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx

The connectionString will vary depending on the Database product and the authentication mechanism used (Windows Auth, username/password, etc.). The example above assumes you are using SQL Server. For a complete list of different ConnectionStrings, go to http://www.connectionstrings.com/

Share:
13,954
Vivendi
Author by

Vivendi

Updated on June 16, 2022

Comments

  • Vivendi
    Vivendi almost 2 years

    How can i execute a SELECT query from my Code Behind file and then iterate through it?

    I want to do something like this (just a simple pseudo example):

    // SQL Server
    var results = executeQuery("SELECT title, name FROM table");
    
    foreach (var row in results)
    {
        string title = row.title;
        string name = row.name;
    }
    

    How can i do this within code?

  • Scarl
    Scarl over 6 years
    this is not viewing anything in my case.