当我点击我的asp.net页面上的按钮时,我试图将数据插入到表中。我没有收到任何错误,但是当我尝试在插入信息后将用户重定向到新页面时,它会保留在同一页面上。以下是我的代码。
SqlConnection db = new SqlConnection();
db.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["AboutYouEntities"].ConnectionString;
db.Open();
SqlCommand insertUser = new SqlCommand();
SqlCommand insertContact = new SqlCommand();
insertUser.CommandText = "INSERT into USER (Email, Name, Gender, BirthDate, LinuxDistro) VALUES ('" + userInfo.Email + "','" + userInfo.Name + "','" + userInfo.Gender + "','" + userInfo.BirthDate + "','" + userInfo.LinuxDistro + "')";
insertContact.CommandText = "INSERT into CONTACT (Phone, Zip, Comments) VALUES ('" + userContact.Phone + "','" + userContact.Zip + "','" + userContact.Comments + "')";
insertUser.ExecuteNonQuery();
insertContact.ExecuteNonQuery();
db.Close();
Response.Redirect("ThankYou.aspx");
答案 0 :(得分:1)
您的代码几乎没有问题:
[USER]
SqlConnection
和SqlCommand
对象括在using
语句中,因为它将确保资源的处置。 代码:
using (SqlConnection db = new SqlConnection())
{
db.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["AboutYouEntities"].ConnectionString;
db.Open();
using (SqlCommand insertUser = new SqlCommand())
{
insertUser.Connection = db;
insertUser.CommandText = "INSERT into [USER] (Email, Name, Gender, BirthDate, LinuxDistro) VALUES (@Email, @Name, @Gender,@BirthDate, @LinuxDistro);";
insertUser.Parameters.AddWithValue("@Email", userInfo.Email);
insertUser.Parameters.AddWithValue("@Name", userInfo.Name);
insertUser.Parameters.AddWithValue("@Gender", userInfo.Gender);
insertUser.Parameters.AddWithValue("@BirthDate", userInfo.BirthDate);
insertUser.Parameters.AddWithValue("@LinuxDistro", userInfo.LinuxDistro);
insertUser.ExecuteNonQuery();
}
using (SqlCommand insertContact = new SqlCommand())
{
insertContact.Connection = db;
insertContact.CommandText = "INSERT into CONTACT (Phone, Zip, Comments) VALUES (@Phone, @Zip, @Comments);";
insertContact.Parameters.AddWithValue("@Phone", userContact.Phone);
insertContact.Parameters.AddWithValue("@Zip", userContact.Zip);
insertContact.Parameters.AddWithValue("@Comments", userContact.Comments);
insertContact.ExecuteNonQuery();
}
}