Preson Reddy
Preson Reddy

Reputation: 36

How to read azure sql db in azure webjob application?

This is my console app. I can zip it and upload it as a webjob,
but I need to read data from my azure db that is published with my .net site

{  static void Main(string[] args)


    { Console.WriteLine("[email protected]");
      MailAddress to = new MailAddress(Console.ReadLine());
 Console.WriteLine("Mail From");
        MailAddress from = new MailAddress(Console.ReadLine());
       MailMessage mail = new MailMessage(from,to );

      Console.WriteLine("Subject");
        mail.Subject = Console.ReadLine()

       Console.WriteLine("Your Message");
        mail.Body = Console.ReadLine()
       SmtpClient smtp = new SmtpClient();
        smtp.Host = "pod51014.outlook.com";
        smtp.Port = 587 
        smtp.Credentials = new NetworkCredential( "*********", "******");
        smtp.EnableSsl = true;

        Console.WriteLine("Sending email...");
        smtp.Send(mail);
    }
}

Is it possible to read azure db in a webjob? If so, how?

Upvotes: 1

Views: 1078

Answers (1)

py3r3str
py3r3str

Reputation: 1879

Yes you can. One way is to add connection string to your App.config file

<configuration>
...
    <connectionStrings>
        <add name="DefaultConnection" connectionString="Data Source=mssql5.webio.pl,2401;Database=ypour_connection_string" providerName="System.Data.SqlClient"/>
    </connectionStrings>
...

And use it in code:

...
String connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (var conn = new SqlConnection(connString))
{
    conn.Open();
    using (SqlCommand command = new SqlCommand(@"your_sql_command"))
    {
         using (SqlDataReader reader = command.ExecuteReader())
         {
             while (reader.Read())
             {
                  //do stuff
             }
         }
    }
}

Upvotes: 2

Related Questions