Search code examples
azureazure-sql-database

azure entity framework: what does a connection string usually look like to login?


I am trying this:

 SqlConnection connection = new SqlConnection(connectionString);

            try
            {
                connection.Open();

                string query = "SELECT * FROM [User]";

                SqlCommand command = new SqlCommand(query, connection);

                command.ExecuteNonQuery();

                Console.WriteLine("Got!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
            finally
            {
                connection.Close();
            }

I have a username and a password with which I can login to my server from SSMS

enter image description here

But I cant figure out what to put into the connection string variable. It must be some sort of combination of my username and password as set in ssms.

Anyone got any help?


Solution

  • azure entity framework: what does a connection string usually look like to login?

    Format of conection string:

    Server=tcp:<server-name>.database.windows.net,1433;Initial Catalog=<database-name>;Persist Security Info=False;User ID=<username>;Password=<your_password>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
    

    To get connection string of Azure SQL server:
    You can go to Settings >> Connection string >> ADO.net >> ADO.NET (SQL authentication) and just replace your password. enter image description here sample code:

    using System;
    using System.Data.SqlClient;
    namespace AzureSqlExample
    {
        class Program
        {
            private static void Main(string[] args)
            {
                string connectionString = "Server=tcp:<server-name>.database.windows.net,1433;Initial Catalog=<database-name>;Persist Security Info=False;User ID=<username>;Password=<your_password>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
    
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
    
                    string query = "SELECT * FROM [tablename]";
                    SqlCommand command = new SqlCommand(query, connection);
    
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Console.WriteLine(reader.GetString(0));
                        }
                    }
                }
                Console.ReadKey();
            }
        }
    }