尝试使用asp.net和c#将数据插入数据库

时间:2014-04-10 20:08:16

标签: c# asp.net sql sql-server code-behind

当我点击我的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");

1 个答案:

答案 0 :(得分:1)

您的代码几乎没有问题:

  • 您尚未连接命令。
  • USER为reserve word,应附在方括号中,如[USER]
  • 您应该parametrized查询,您很容易SQL Injection
  • 考虑将SqlConnectionSqlCommand对象括在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();
    }
}