我有一个简单的测试数据库,它有一个名为 ID 的列,它是一个带有自动标识集的主键。
我正在尝试向使用 sqladapter 创建的数据表添加新行
当我将新行的 ID 列留空时,认为 sql 会添加它,它会显示以下错误:
"Column "ID" doesn't not allow nulls
我解决了它,但给 ID 任何值,比如dr["ID"] = 99999
它起作用了,但是现在 SQL 数据库忽略了该值并只给它正确的数字,但数据表的 ID 为 99999,这使它有点混乱,如果我尝试插入另一条记录,可能会抛出错误
我怎么解决这个问题?
对于那个很抱歉:
DataRow dr = dt.NewRow();
dr["Name"] = "fds";//E.Name;
dr["Age"] = 12;// E.Age;
dr["DateOfBirth"] = "1-1-1999";// E.DoB;
//dr["ID"] = 99999;
dt.Rows.InsertAt(dr, dt.Rows.Count - 1);
DBOperations.UpdateTable(dt);
MessageBox.Show("Record added successfully");
static internal void UpdateTable(DataTable dt)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlDataAdapter Adapter = new SqlDataAdapter();
Adapter.SelectCommand = new SqlCommand("select * from Emp",con);
Adapter.UpdateCommand = new SqlCommandBuilder(Adapter).GetUpdateCommand();
Adapter.InsertCommand = new SqlCommandBuilder(Adapter).GetInsertCommand();
Adapter.DeleteCommand = new SqlCommandBuilder(Adapter).GetDeleteCommand();
Adapter.Update(dt);
}
数据库脚本:
USE [HR]
GO
/****** Object: Table [dbo].[Emp] Script Date: 2/12/2013 8:10:49 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Emp](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NOT NULL,
[Age] [int] NOT NULL,
[DateOfBirth] [date] NOT NULL,
CONSTRAINT [PK_Emp] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
截屏: