C# 如何在数据库中插入主键?

C# 如何在数据库中插入主键?,c#,winforms,C#,Winforms,因为emp_id是pk,并且没有文本框 cmd.CommandText = "INSERT INTO cntc_employee (emp_id,emp_f_name,emp_l_name,emp_alias,emp_contact_no,emp_address,emp_company,emp_bdate) VALUES(@fname,@lname,@alias,@contact,@address,@company,@bdate)"; cmd.Connection = con; cmd.Para

因为
emp_id
是pk,并且没有文本框

cmd.CommandText = "INSERT INTO cntc_employee (emp_id,emp_f_name,emp_l_name,emp_alias,emp_contact_no,emp_address,emp_company,emp_bdate) VALUES(@fname,@lname,@alias,@contact,@address,@company,@bdate)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("@empid", ????);
cmd.Parameters.AddWithValue("@fname", textBox1.Text);
cmd.Parameters.AddWithValue("@lname", textBox2.Text);
cmd.Parameters.AddWithValue("@alias", textBox3.Text);
cmd.Parameters.AddWithValue("@contact", textBox4.Text);
cmd.Parameters.AddWithValue("@address", textBox5.Text);
cmd.Parameters.AddWithValue("@company", textBox6.Text);
对于
empid
我不知道使用哪个命令


cmd.Parameters.AddWithValue(“@empid”,?)

如果
EmpId
在SQL中是
Identity
,则无需传递它

cmd.CommandText=“插入cntc_员工(emp_f_姓名、emp_l_姓名、emp_别名、emp_联系人编号、emp_地址、emp_公司、emp_bdate)值(@fname、@lname、@alias、@contact、@address、@company、@bdate)”

如果不是,则需要在编程语言中提及或生成逻辑以创建Emp ID

如果
Emp\u ID
是自动生成的主键,只需不在列列表中指定它(因此没有理由提供绑定值)-这包括SQL Server中的列和MySQL中的列等

// Additional columns removed for sake of example
cmd.CommandText = "INSERT INTO cntc_employee (emp_f_name) values (@fname)";
cmd.Parameters.AddWithValue("@fname", textBox1.Text);
假设是这种情况,则数据库将看到
emp_id
未分配值,并将在插入记录时为列使用“下一个”可用值


如果
emp\u id
不是自动生成的代理密钥,那么找出是谁设计了系统,并询问他们该值是什么以及该值应如何生成:)

如果您希望emp id自动增加,则必须设置其标识

若您使用的是MSSQL,那个么使用下图来设置表的标识


如果出于某种原因确实想在字段emp\u id中插入特定值,则必须将Identity\u insert设置为on

// "SET IDENTITY_INSERT [ database_name . [ schema_name ] . ] table { ON | OFF }"

cmd.CommandText = "SET IDENTITY_INSERT dbo.cntc_employee ON; ";
cmd.CommandText += "INSERT INTO cntc_employee (emp_id,emp_f_name,emp_l_name,emp_alias,emp_contact_no,emp_address,emp_company,emp_bdate) VALUES(@empid,@fname,@lname,@alias,@contact,@address,@company,@bdate)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("@empid", textBoxXx.Text);
cmd.Parameters.AddWithValue("@fname", textBox1.Text);
cmd.Parameters.AddWithValue("@lname", textBox2.Text);
cmd.Parameters.AddWithValue("@alias", textBox3.Text);
cmd.Parameters.AddWithValue("@contact", textBox4.Text);
cmd.Parameters.AddWithValue("@address", textBox5.Text);
cmd.Parameters.AddWithValue("@company", textBox6.Text);

你是什么意思?要插入的
empid
的值是什么?如果没有文本框,那么该值来自何处?在这里,你的意思是说它是由数据库自动生成的(即
identity
列)?你需要在那里输入empid的值。如果列是自动递增列(identity),那么你应该离开该列。你设置了主键的标识了吗?