C# 未使用dataadapter将数据插入sql数据库。。?

C# 未使用dataadapter将数据插入sql数据库。。?,c#,sql,database,ado.net,C#,Sql,Database,Ado.net,这是密码 string constr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Inventory.mdf;Integrated Security=True;User Instance=True"; SqlConnection con = new SqlConnection(constr); try { SqlDataAdapter sda =

这是密码

string constr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Inventory.mdf;Integrated Security=True;User Instance=True";
        SqlConnection con = new SqlConnection(constr);
        try
        {
            SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Users", con);
            DataSet ds = new DataSet();
            con.Open();
            SqlCommandBuilder cmd = new SqlCommandBuilder(sda);
            sda.Fill(ds, "Users");
            DataRow row = ds.Tables["Users"].NewRow();
            row[0] = 2;
            row[1] = txtUsername.Text;
            row[2] = txtPassword.Text;
            ds.Tables["Users"].Rows.Add(row);
            int res=sda.Update(ds, "Users");
            con.Close();
            sda.Dispose();
            dgUser.ItemsSource = null;
            dgUser.ItemsSource = ds.Tables["Users"].DefaultView;
            ds.Dispose();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            if (con.State == ConnectionState.Open)
                con.Close();
            con.Dispose();
        }

问题是它执行时没有错误,但当您签入数据库时,将不会插入记录。。。可能有什么错误?

老实说,我没有看到代码中有任何错误。是否可以尝试使用断点进行调试,并查看在将行传递到DB之前是否已正确添加到数据集?

是否已为DataAdapter配置了?如果不设置它,适配器就不可能知道插入您的记录

你需要像这样的东西

cmd ="INSERT INTO ...."; // add param to this

sda.InsertCommand = cmd

设置此选项后尝试更新。(如果需要,对适配器的
UpdateCommand
执行类似操作)

尝试执行插入而不是选择

    SqlDataAdapter sda = new SqlDataAdapter("insert into Users (ID, UserName, Password) VALUES (2," + 
       txtUsername.Text + ", " + txtPassword.Text + ")", con);

但是内联SQL通常是个坏主意。最好是编写一个存储过程并从代码中执行它

您是否检查ds是否正在获取用户的表记录?我尝试用我的表执行您的代码,它工作正常。实际上它没有插入,但它可以显示表中的数据。他正在使用SqlDataAdapter的更新方法。他不需要配置Insert或Update命令。@nevayshirazi我认为这只适用于使用
SelectCommand
的情况,否则您必须…您是对的,我刚刚在MSND上看到了它,但他的代码在我的电脑上运行得很好。我也尝试过。。cmd.ExecuteNonQuerry()返回一行受影响但未将数据插入到表中。在sql server management studio中使用相同语法时,是否可以插入?使用相同的登录凭证是的。。我也试过了。。数据集与行一起添加。sda.update返回一行受影响。。但数据不会添加到表中