C# Adapter.Update()不起作用?

C# Adapter.Update()不起作用?,c#,ado.net,dataadapter,C#,Ado.net,Dataadapter,我使用此代码向Customer表插入内容,但它不起作用? 我的数据库不更新,r的值始终为0` using (SqlConnection cn = new SqlConnection(con)) { cn.Open(); string query = string.Format("Select * From Customers"); SqlDataAdapter adapter = new SqlDataAd

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

`您没有向数据集/数据表添加行,因此有
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");
}

我想你应该多看看ado.net。或者执行查询以执行插入,或者如果使用数据适配器,则需要将行添加到数据集中