Sql 数据库不更新更改

Sql DataBase does not update changes

我收到以下错误消息

Dynamic sql generation for the update command is not supported against a select command that does not return any key column information

当我在 GridView 中进行更改后尝试通过单击按钮更新我的数据库时。下面是代码:

private void updateDB_Click(object sender, EventArgs e)
{
    SqlDataAdapter sqlAdapter = new SqlAdapter(@"SELECT [Customer],[Employee],[Product],[State] FROM [Table1]", connection);
    sqlCmdBuilder = new SqlCommandBuilder(sqlAdapter);
    DataTable datTable = dataGridView1.DataSource as DataTable;
    sqlAdapter.Update(datTable);
}

我进行了很多搜索以找到解决方案,但找不到有用的东西。我知道这是因为我的数据库中缺少 PrimaryKey,但应该有 none。

那么,在没有定义 PrimaryKey 的情况下,如何在进行更改后更新我的数据库?是否可以使用另一种方式,我只能使用我的列名和表名(我只找到了一个解决方案,其中每个元素都必须手动编写,这太多了)?

"a Primary Key is missing in my database but it is supposed that there is none"

这是你的问题。没有主键,DataAdapter 无法计算出要更新哪一行,因此当您尝试时会失败。

正如您所指出的,您可以手动编写更新 SQL,但是如果您有一个 table 包含需要单独更新的行,那么主键是可行的方法。

使用此代码,您将更新 DataTable,而不是您的数据库。你可以阅读这篇Article

  SqlDataAdapter sqlAdapter = new SqlAdapter(@"SELECT [Customer],[Employee],[Product],[State] FROM [Table1]", connection);
  sqlCmdBuilder = new SqlCommandBuilder(sqlAdapter);
  DataTable datTable = dataGridView1.DataSource as DataTable;
  sqlAdapter.Update(datTable);
  sqlAdapter.Dispose();// SqlDataAdapter must be Disposed !

根据你的问题

when I try to update my database via a button

如果您想更新数据库,您需要更新查询并调用 SqlCommand 的 ExecuteNonQuery()。您应该 Insert/Update 使用 adding/updating 网格中的任何记录进入您的数据库。