0

我正在尝试根据用户的输入升级数据库,但它不起作用......

我正在使用这个:

 protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(strcon);
    SqlCommand cmd = new SqlCommand();
    SqlCommand ncmd = new SqlCommand("Update Utenti Set Nome = @vnome where [Indirizzo E-Mail]=@vem", con);
    ncmd.Parameters.AddWithValue("@vem", Session["[Indirizzo E-Mail]"].ToString());
    ncmd.Parameters.AddWithValue("@vnome", TextBox2.Text);
    ncmd.Connection = con;
    con.Open();
    ncmd.ExecuteNonQuery();
    con.Close();
    Label2.Text = "Dati aggiornati con successo!";
    Response.Redirect("~/ModificaDati.aspx");
}

当我单击按钮时,它显示 Label2 文本,但在数据库中“Nome”没有改变,为什么?谢谢之前的回答^^

4

3 回答 3

0

你的代码看起来不错。只要确保按照 Damith 的建议检查 SQL 是否正确。

我推荐的另一件事是在执行查询之前另外验证数据类型正确性的参数。使用这种方法,您可能会避免很多不必要的异常,并且能够提供更多用户友好的消息。当然,这仅适用于用户输入为非文本类型的情况

//Data Type verification
DateTime tmp;
if (!DateTime.TryParse(Label2.Text.Trim(), out tmp))
{ 
  //Show error message that this is not a correct data type
}
于 2013-07-25T11:39:24.973 回答
0

我会改变你的方法如下

if (Session["[Indirizzo E-Mail]"] != null &&
    !string.IsNullOrEmpty(Session["[Indirizzo E-Mail]"].ToString()) &&
    !string.IsNullOrEmpty(TextBox2.Text))
{
    string vem = Session["[Indirizzo E-Mail]"].ToString(); 
    using (var con = new SqlConnection(strcon))
    using (var ncmd = new SqlCommand("Update Utenti Set Nome = @vnome where [Indirizzo E-Mail]=@vem", con))
    {
        con.Open();
        ncmd.Parameters.AddWithValue("@vem", vem);
        ncmd.Parameters.AddWithValue("@vnome", TextBox2.Text);
        int rows  = ncmd.ExecuteNonQuery();
        Label2.Text = rows  + " Dati aggiornati con successo!";
    }
}

Response.Redirect("~/ModificaDati.aspx");
  1. 添加了输入验证,会话值可以为空,最好在更新数据库之前检查
  2. 创建SqlCommand时可以给连接,无需重新设置
  3. 确保您的 SQL 有效
  4. 对一次性对象使用using语句,例如SqlConnection, SqlCommand
于 2013-07-25T03:15:53.083 回答
-1

先打开你的连接

con.Open();

ncmd.Connection = con;

希望能帮助到你

于 2013-07-25T02:39:49.953 回答