csharp数据库问题

csharp的数据库再插入操作时报错
Cannot insert the value NULL into column 'Id', table 'BookTestBb.dbo.Book'; column does not allow nulls. INSERT fails.
The statement has been terminated.

img

Id 字段不存在,有两种解决方法
1.修改插入语句,增加id字段
2.修改数据表,设置id为自增字段

根据报错信息,可能是在执行数据库插入操作时,插入的数据中缺少了必要的字段值。在上面的报错信息中,缺少的字段是Id,它在数据表BookTestBb.dbo.Book中不允许为空。因此,在执行插入操作时,需要确保插入的数据中包含了所有的非空字段。

  • 例如,如果你在C#中使用ADO.NET来执行插入操作,可以这样写代码:

    using (SqlConnection conn = new SqlConnection(connectionString))
    {
      string sql = "INSERT INTO Book (Id, Title, Author, Price) VALUES (@id, @title, @author, @price)";
      using (SqlCommand cmd = new SqlCommand(sql, conn))
      {
          cmd.Parameters.AddWithValue("@id", 1);
          cmd.Parameters.AddWithValue("@title", "book title");
          cmd.Parameters.AddWithValue("@author", "author name");
          cmd.Parameters.AddWithValue("@price", 19.99);
    
          conn.Open();
          cmd.ExecuteNonQuery