Querying Azure SQL Database items

In this part of the demonstration, we are going to query the database. The following code will show you how to run a query against the items that we stored in the database in the previous step.

Therefore, we need to take the following steps:

  1. Copy and paste the QueryItems method after your AddItemsToDatabase method. Create the connection again, and create the query, as follows:
  static void QueryItems()
{
connection = new SqlConnection(connectionstring);

using (connection)
{
try
{
Console.WriteLine(" Querying database:");
Console.WriteLine("========================================= ");


var cmd = new SqlCommand("SELECT * FROM Employee WHERE LastName = @LastName", connection);
cmd.Parameters.AddWithValue("@LastName", NewEmployee.LastName);
  1. Then, open the connection, execute the query, and close the connection. Write some values to the console app, as follows:
                    connection.Open();
cmd.ExecuteNonQuery();

using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Console.WriteLine(reader.GetValue(i));
}
}
connection.Close();
}
Console.WriteLine(" Finsihed querying database:");
Console.WriteLine("========================================= ");
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
}
}
  1. Then, we need to call QueryItems in the GetStartedDemo method again, as follows:
 static void GetStartedDemo()
{
connectionstring = "<replace-with-your-connectionstring>";
connection = new SqlConnection(connectionstring);

AddItemsToDatabase();

//ADD THIS PART TO YOUR CODE
QueryItems();
}
  1. Run the application, and you will see the query results displayed in the console.

We have now created a query to retrieve the data from the database. In the next section, we are going to update the Employee item.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset