ProgrammingRookie
ProgrammingRookie

Reputation: 191

Data is not being inserted into SQL Server Database hosted on Azure

I have a SQL Server database which is hosted on Azure. I am trying to input data into a table using C# and for some reason that data is not appearing in the table. Here is the code I am using. I don't know if the problem is in the connection string or something else. Any ideas?

   //string connection = ("user id=MyGoals;" + "Password=pass;" + "Server=tcp:vclr5u6rk6.database.windows.net;" + "Trusted_Connection=yes;" + "Database=myGoals;" + "connection timeout=30");
            string connection = "Server=tcp:vclr5u6rk6.database.windows.net, 1433; Database=myGoals;Uid=MyGoals;Pwd=pass;";
            SqlConnection conn = new SqlConnection(connection);
            conn.OpenAsync();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "INSERT INTO Users(FirstName, SecondName, Password, Email, DOB) values (@fn, @sn, @pass, @email, @dob)";
            string firstname = Page.Request.Form["firstname"].ToString();
            string secondname = Page.Request.Form["secondname"].ToString();
            string email = Page.Request.Form["email"].ToString();
            string password = Page.Request.Form["password"].ToString();
            string birthday = Page.Request.Form["birthday"].ToString();
            cmd.Parameters.AddWithValue("@fn", firstname);
            cmd.Parameters.AddWithValue("@sn", secondname);
            cmd.Parameters.AddWithValue("@pass", password);
            cmd.Parameters.AddWithValue("@email", email);
            cmd.Parameters.AddWithValue("@dob", birthday);
            cmd.ExecuteNonQueryAsync();
            conn.Close();

Upvotes: 1

Views: 636

Answers (1)

Martin Costello
Martin Costello

Reputation: 10862

You're not using the await operator on your *Async() calls, so the code is executing incorrectly as it is not waiting for the operations (e.g. opening the connection) to complete. Either make the method async and use the await operator, or don't use the *Async() methods as they are returning a task for the actions to be done at some point later that you aren't waiting on to complete.

For example:

 public async Task Foo()
 {
     /// <snip />

     await conn.OpenAsync();

     /// <snip />

     await cmd.ExecuteNonQueryAsync();

     /// <snip />
 }

or:

 public void Foo()
 {
     /// <snip />

     conn.Open();

     /// <snip />

     cmd.ExecuteNonQuery();

     /// <snip />
 }

Upvotes: 3

Related Questions