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?
我有一个托管在Azure上的SQL Server数据库。我正在尝试使用C#将数据输入到表中,并且出于某种原因,数据未出现在表中。这是我正在使用的代码。我不知道问题是在连接字符串中还是其他内容。有任何想法吗?
//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();
1 个解决方案
#1
3
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.
您没有在* Async()调用上使用await运算符,因此代码执行不正确,因为它不等待操作(例如打开连接)完成。要么使方法异步并使用await运算符,要么不使用* Async()方法,因为它们返回一个任务,以便稍后您不等待完成的操作完成。
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 />
}
#1
3
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.
您没有在* Async()调用上使用await运算符,因此代码执行不正确,因为它不等待操作(例如打开连接)完成。要么使方法异步并使用await运算符,要么不使用* Async()方法,因为它们返回一个任务,以便稍后您不等待完成的操作完成。
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 />
}