如何通过 C# 将值插入 SQL 中的主键标识列? [英] How to insert value into primary key identity column in SQL through C#?

查看:30
本文介绍了如何通过 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 中的主键标识列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆