如何通过 C# 将值插入 SQL 中的主键标识列?

How to insert value into primary key identity column in SQL through C#?(如何通过 C# 将值插入 SQL 中的主键标识列?)
本文介绍了如何通过 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();

任何帮助将不胜感激.

推荐答案

你可以忽略 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 中的主键标识列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)