Adapter.Update()不起作用?

时间:2016-04-27 11:50:44

标签: c# ado.net dataadapter

我使用此代码将一些内容插入到客户表中,但它不起作用? 我的数据库没有更新,r的值总是为0.`

 using (SqlConnection cn = new SqlConnection(con))
        {
            cn.Open();
            string query = string.Format("Select * From Customers");
            SqlDataAdapter adapter = new SqlDataAdapter();
            SqlCommandBuilder cb = new SqlCommandBuilder(adapter);


            adapter.SelectCommand = new SqlCommand(query, cn);
            DataSet db = new DataSet();
            adapter.Fill(db,"Customers");

            string m = "Bon app'" ,city="london";
            query = string.Format("Insert Into Customers (CompanyName , City) Values ('{0}','{1}')",m,city);
            adapter.InsertCommand =new  SqlCommand(query, cn);

            int r= adapter.Update(db,"Customers");

         Console.WriteLine(r);

`

1 个答案:

答案 0 :(得分:1)

您不会向DataSet / DataTable添加行,因此DataAdapter无需插入任何内容。

db.Tables[0].Rows.Add(m, city);
int r = adapter.Update(db,"Customers");

除此之外,不要连接字符串来构建您的SQL查询。使用参数化查询。

所以这是一个使用sql-parameters的修改版本:

using (SqlConnection cn = new SqlConnection(con))
{
    cn.Open();
    string selectQuery = "Select * From Customers";
    string insertQuery = "Insert Into Customers (CompanyName , City) Values (@CompanyName, @City)";
    SqlDataAdapter adapter = new SqlDataAdapter();
    adapter.SelectCommand = new SqlCommand(selectQuery, cn);
    adapter.InsertCommand = new SqlCommand(insertQuery, cn);
    DataSet db = new DataSet();
    adapter.Fill(db, "Customers");

    var icp = adapter.InsertCommand.Parameters;
    icp.Add("@CompanyName", SqlDbType.NVarChar, 150, "CompanyName"); // optional, restrict length according to database max-length
    icp.Add("@City", SqlDbType.NVarChar, 100, "City"); 

    DataRow newRow = db.Tables["Customers"].Rows.Add();
    newRow.SetField("CompanyName", "Bon app");
    newRow.SetField("City", "london");
    int r = adapter.Update(db, "Customers");
}