Connection.Open();
SqlCommand Command = new SqlCommand(null, Connection);
Command.CommandText = "Insert into [EmployeeTable] (Forename,Surname,DateofBirth,Email address,Country,Address,City,Postcode,Skill1,Skill2,Skill3,Job1,Job 2,Job3,EmployeeAvailability) Values(@forename, @surname, @dateofbirth, @emailaddress, @phonenumber, @country, @address, @city, @postcode, @skill1, @skill2, @skill3, @job1, @job2, @job3, @employeeavailability)";
Command.Parameters.AddWithValue("@forename", ForenameInputBox.Text);
Command.Parameters.AddWithValue("@surname", SurnameInputBox.Text);
Command.Parameters.AddWithValue("@dateofbirth", DoBInputBox.Text);
Command.Parameters.AddWithValue("@emailaddress", EmailInputBox.Text);
Command.Parameters.AddWithValue("@country", CountryInputBox.Text);
Command.Parameters.AddWithValue("@address", AddressInputBox.Text);
Command.Parameters.AddWithValue("@city", CityInputBox.Text);
Command.Parameters.AddWithValue("@postcode", PostcodeInputBox.Text);
Command.Parameters.AddWithValue("@skill1", Skill1InputBox.Text);
Command.Parameters.AddWithValue("@skill2", Skill2InputBox.Text);
Command.Parameters.AddWithValue("@skill3", Skill3InputBox.Text);
Command.Parameters.AddWithValue("@job1", Job1InputBox.Text);
Command.Parameters.AddWithValue("@job2", Job2InputBox.Text);
Command.Parameters.AddWithValue("@job3", Job3InputBox.Text);
Command.Parameters.AddWithValue("@employeeavailability", EmployeeAvailablityBox.Text);
Command.ExecuteNonQuery();
Connection.Close();
}
}
CREATE TABLE [dbo].[EmployeeTable] (
[EmployeeID] INT NOT NULL,
[Forename] NVARCHAR (50) NOT NULL,
[Surname] NVARCHAR (50) NOT NULL,
[DateofBirth] DATETIME NOT NULL,
[Emailaddress] NVARCHAR (50) NOT NULL,
[Country] NVARCHAR (50) NOT NULL,
[Address] NVARCHAR (50) NOT NULL,
[City] NVARCHAR (50) NOT NULL,
[Postcode] NVARCHAR (50) NOT NULL,
[Skill1 ] NVARCHAR (50) NOT NULL,
[Skill2] NVARCHAR (50) NOT NULL,
[Skill3] NVARCHAR (50) NOT NULL,
[Job1] BIT NOT NULL,
[Job2] BIT NOT NULL,
[Job3] BIT NOT NULL,
[EmployeeAvailability] BIT NOT NULL,
PRIMARY KEY CLUSTERED ([EmployeeID] ASC)
);
我创建了一个表来存储员工的详细信息,但是在尝试保存输入时会出现错误消息。 错误消息如下:
类型' System.Data.SqlClient.SqlException'未处理的异常发生在System.Data.dll中附加信息:无法将值NULL插入列' EmployeeID',table' C:\ USERS \ USER \ DOCUMENTS \ VISUAL STUDIO 2015 \ PROJECTS \ WPFAPPLICATION \ WPFAPPLICATION1 \ EMPLOYEEDB.MDF. dbo.EmployeeTable&#39 ;;列不允许空值。 INSERT失败。该声明已被终止
我认为这是因为没有任何值输入到EmployeeID字段中,所以如何设置它以便每次生成一个新的员工ID并填充该字段,假设这是错误消息的原因?
答案 0 :(得分:0)
标准方法是将列设为IDENTITY
列:
[EmployeeID] INT IDENTITY(1,1),
然后数据库将自动生成每个插入的数字。这具有保证唯一性的额外好处,这一点很重要,因为此列也用作主键。由于IDENTITY
始终是一个增加的值,因此成为CLUSTERED
索引也会很好。