本文介绍了将InsertCommand内code背后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在code遇到了followng code的后面,不知道如果这可能是插入一条记录方面一个很好的做法编程方式:

I came across the followng code in the code behind and wondering if this may be a good practice in terms of inserting a record programmatically:

protected void ButtonMain_Click(object sender, EventArgs e)
{

    string sConn = ConfigurationManager.ConnectionStrings["SQL1"].ConnectionString;
    SqlDataSource dbQ = new SqlDataSource();
    dbQ.ConnectionString = sConn;
    dbQ.InsertCommand = "INSERT INTO data1_DropDownLists (ParamID, ddlValue) VALUES ('" + ddlAllParams.SelectedValue + "','" +
        txtddl.Text + "')";
    dbQ.Insert();
    DropDownGrid.DataBind();
    dbQ = null;

}

我所看到的是以前是一样的东西:

What I have seen is before is something like:

     string query = "INSERT INTO data1_DropDownLists vALUES ...";
     cmd = new SqlCommand(query, conn);
     conn.Open();
     cmd.ExecuteNonQuery();

所以不知道的好处可能是使用使用的InsertCommand上面的方法是什么

so was not sure of what the benefit may be to using the above method using InsertCommand

推荐答案

的SqlDataSource 是在System.Web命名空间的控制。它可以用作数据源的Web数据绑定控件,如转发的GridView

这是一个应该被声明的ASPX标记,而不是用在codebehind控制。这就像GUI和DAL之间的接口。通常情况下,你应该避免这种hardlinking的。相反,你应该分开GUI(Java),BLL(codebehind或类库等)和DAL(或ADO.NET实体框架等)。

It is a control which should be used declaratively on the aspx markup and not in codebehind. It's like an interface between the GUI and the DAL. Normally you should avoid this kind of hardlinking. Instead you should separate GUI(ASPX), BLL(codebehind or class libraries etc.) and DAL (ADO.NET or Entity framework etc.).

我会建议用最直接的方式,使用ADO.NET 的SqlCommand

I would suggest to use the most direct way, using an ADO.NET SqlCommand:

// use using-statement to ensure that the connection gets closed even in case of an error
using (var con = new SqlConnection(connectionString))
{
    using (var cmd = new SqlCommand("INSERT INTO dbo.Table(Column)VALUES(@Column)", con))
    {
        // use parameters to avoid SQL-Injection
        cmd.Parameters.AddWithValue("@Column", value);
        con.Open();
        cmd.ExecuteNonQuery();
    }
}

这篇关于将InsertCommand内code背后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 22:48