【问题标题】:Save and Update statements no longer work保存和更新语句不再起作用
【发布时间】:2013-11-15 14:07:21
【问题描述】:

在我的代码中插入非常必要的行之后-

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
      try {


        GridViewRow row = GridView1.SelectedRow; 

            AccountNumber.Text = (string)row.Cells[0].Text;
           .....
            if (DropDownListCurrency.Items.FindByValue(row.Cells[7].Text.ToString().Trim()) != null)
            {
                DropDownListCurrency.SelectedValue = row.Cells[7].Text.ToString().Trim();

            }
      }

      catch (Exception ex)
      {
          Console.WriteLine("{0} Exception caught.", ex);
      }

    }

没有抛出任何错误,所有字段都按应有的方式填充到相应的下拉框和文本框中。但是我的保存和插入语句不再起作用。帮忙!

  protected void AgentSave_Click(object sender, EventArgs e)
    {
    try
        {

            SqlConnection con = new SqlConnection("XX");
            SqlCommand command = con.CreateCommand();
            command.CommandText =
                "Insert into ABC values('" + AccountNumber.Text + "','" + Name.Text + "','" + Address1.Text + "','" + Address2.Text + "', '" + Address3.Text + "','" + PhoneNumber.Text + "','" + FaxNumber.Text + "','" + DropDownListCurrency.Text + "')";
            con.Open();
            command.ExecuteNonQuery();  
            con.Close();


            Response.Redirect("main.aspx");

            }

        catch (Exception ex)
        {
            Console.WriteLine("{0} Exception caught.", ex);
        }
     }

【问题讨论】:

  • 一定要参数化你的sql查询以避免sql注入攻击:en.wikipedia.org/wiki/SQL_injection
  • 他们是。在我插入此语句之前它们工作正常,但现在它们不是......
  • 请使用参数化sql查询,避免sql注入攻击。请分享您的完整代码。
  • 能否请您在XXX 中填写一些更具体的代码?您是否指定了列名?
  • @New2This - 您没有处理您的 SqlConnection 对象。将其包装在 using 语句中。这可能就是您遇到问题的原因。

标签: c# asp.net sql visual-studio-2010


【解决方案1】:

这可能不是答案。在 cmets 中传达代码更改变得太困难了

您需要像这样处理您的 SqlConnection:

        using (var con = new SqlConnection("XX"))
        {
            SqlCommand command = con.CreateCommand();
            command.CommandText = "INSERT ABC VALUES(@AccountNumber, @Name, ";//...you need to fill in all the parameters
            command.Parameters.Add("@AccountNumber", SqlDbType.Text);//Pick proper SqlDbType...whatever it is I dunno
            command.Parameters["@AccountNumber"].Value = AccountNumber.Text;
            //rinse and repeat for rest of params
            con.Open();
            command.ExecuteNonQuery();                
        }//using will automatically correctly close and dipose of the connection when con goes out of scope.

【讨论】:

  • 它不工作。仍然不允许我使用下拉列表更新值或保存新记录。
  • @New2This - 什么是错误?你可以运行sql profiler来查看是否正在查询数据库吗?您是否尝试过通过 SSMS 直接插入?
猜你喜欢
  • 1970-01-01
  • 2023-02-11
  • 2015-07-16
  • 2017-09-27
  • 1970-01-01
  • 1970-01-01
  • 2018-04-16
  • 1970-01-01
相关资源
最近更新 更多