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:
- 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);
- 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());
}
}
}
- 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();
}
- 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.