Connecting to the Azure SQL database

  1. Open Visual Studio, and create a new console app (.NET) project.
  2. Name the project PacktSQLApp.
  3. Right-click on your project in the Solution Explorer, and select Manage NuGet Packages.
  4. Select Browse, search for System.Data.SqlClient, and install the package.
  5. Open Program.csand replace the references with the following:
using System;
using System.Data.SqlClient;
  1. Add the following variable in the Program.cs method:
static string connectionstring;
  1. Now, go back to the Azure portal. Navigate to the Azure SQL database that we created in the previous section. Under Settings, select Connection strings. Copy the connection string, as follows:

SQL database connection string
  1. Below the Main method, add a new asynchronous task called GetStartedDemoAsync, which instantiates our new SqlConnection. We use GetStartedDemoAsync as the entry point that calls methods operating on Azure Cosmos DB resources. In the method, replace <replace-with-your-connectionstring>  with the connection string that you copied. Also, in the connection string, replace {your-username} with the username you specified when you created the database, and replace {your-password} with the password you provided, as follows:
   static void GetStartedDemo()
{
connectionstring = "<replace-with-your-connectionstring";
}
  1. Add the following code, to run the GetStartedDemo  synchronous task from your Main method:
   static void Main(string[] args)
{
try
{
Console.WriteLine("Beginning operations... ");
GetStartedDemo();

}
catch (SqlException de)
{
Exception baseException = de.GetBaseException();
Console.WriteLine("{0} error occurred: {1}", de.Message, de);
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e);
}
finally
{
Console.WriteLine("End of demo, press any key to exit.");
Console.ReadKey();
}
}

Now that we have successfully added the connection string to the Azure SQL database, we can create some data in the new database.

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

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