Search code examples
asp.netasp.net-3.5code-behind

Execute select query from code behind


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?


Solution

  • 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/