如何通过C#将值插入SQL的主键标识列中? [英] How to insert value into primary key identity column in SQL through C#?
本文介绍了如何通过C#将值插入SQL的主键标识列中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
(我的问题解决了。几乎每个人都说我必须删除@OB_ID并留给SQL分配值。)
(My problem solved. As almost everyone said I had to remove @OB_ID and left it to SQL to assign value.)
我想插入一条新记录通过C#代码导入SQL数据库中的表。主键是身份。如何使Visual Studio理解该列是标识,因此SQL Server必须设置该值。以下是相关代码:
I want to insert a new record into a table in SQL database through C# code. The primary key is identity. How can I make Visual Studio understood that the column is identity so SQL Server must set the value. Here's the related code:
SqlConnection sqlc = new SqlConnection();
sqlc.ConnectionString = "Data Source=. ; Database=LDatabase; Integrated Security=true;";
SqlCommand cmd2 = new SqlCommand("INSERT INTO Order_Book VALUES(@OB_ID, @OB_Title, @OB_Author, @OB_TranslatedBy, @OB_Publisher)", sqlc);//@OB_ID is indentity primary key
cmd2.Parameters.AddWithValue("@OB_ID", );//What should I assign to it?
cmd2.Parameters.AddWithValue("@OB_Title", "%" + txtboxbook.Text + "%");
cmd2.Parameters.AddWithValue("@OB_Author", "%" + txtboxAuthor.Text + "%");
cmd2.Parameters.AddWithValue("@OB_TranslatedBy", "%" + txtboxTranslator.Text + "%");
cmd2.Parameters.AddWithValue("@OB_Publisher", "%" + txtboxPublisher.Text + "%");
sqlc.Open();
cmd2.ExecuteNonQuery();
sqlc.Close();
任何帮助将不胜感激。
Any help would be appreciated.
推荐答案
您可以忽略 IDENTITY
列,因为它将插入默认情况下
。
you can ignore IDENTITY
column as it will be inserted by default
.
尝试一下
SqlConnection sqlc = new SqlConnection();
sqlc.ConnectionString = "Data Source=. ; Database=LDatabase; Integrated Security=true;";
SqlCommand cmd2 = new SqlCommand("INSERT INTO Order_Book VALUES(@OB_Title, @OB_Author, @OB_TranslatedBy, @OB_Publisher)", sqlc);//@OB_ID is indentity primary key
cmd2.Parameters.AddWithValue("@OB_Title", "%" + txtboxbook.Text + "%");
cmd2.Parameters.AddWithValue("@OB_Author", "%" + txtboxAuthor.Text + "%");
cmd2.Parameters.AddWithValue("@OB_TranslatedBy", "%" + txtboxTranslator.Text + "%");
cmd2.Parameters.AddWithValue("@OB_Publisher", "%" + txtboxPublisher.Text + "%");
sqlc.Open();
cmd2.ExecuteNonQuery();
sqlc.Close();
这篇关于如何通过C#将值插入SQL的主键标识列中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文