Adapter.Update() 不起作用?

Adapter.Update() does not work?

我使用此代码向客户插入内容 Table 但它不起作用? 我的数据库没有更新,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);

`

您没有向 DataSet/DataTable 添加行,因此 DataAdapter 没有可插入的内容。

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

除此之外,请勿连接字符串来构建 sql 查询。使用参数化查询。

所以这是一个使用 sql 参数的修改版本:

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");
}