简体   繁体   English

使用 C# 插入 SQL 服务器表

[英]Insert into SQL Server table using C#

I am using the following code in order to insert some data into my SQL Server table.我正在使用以下代码将一些数据插入到我的 SQL 服务器表中。 There isn't any error shown, but the table doesn't insert the values.没有显示任何错误,但表没有插入值。 What is wrong with it?它有什么问题?

string sqlTxt1 = "INSERT INTO Users (ChatId , UserName) VALUES (@ChatId, @from)";

SqlCommand cmd1 = new SqlCommand(sqlTxt1, con);
cmd1.Parameters.AddWithValue("@ChatId", 12345);
cmd1.Parameters.AddWithValue("@from", "usrnm");

con.Open();
cmd1.ExecuteNonQuery();
//int recordsAffected =cmd1.ExecuteNonQuery();
con.Close();

As I put the code in a button and set the ChatId in the table as a primary key, I get an error when I click it twice, so I think the code is correct, but why the table doesn't get those values in the first click?当我将代码放在一个按钮中并将表中的ChatId设置为主键时,当我单击它两次时出现错误,所以我认为代码是正确的,但是为什么表中没有得到这些值第一次点击?

It should be string sqlTxt1 = "INSERT INTO Users (ChatId, UserName) VALUES (@ChatId, @from)";它应该是string sqlTxt1 = "INSERT INTO Users (ChatId, UserName) VALUES (@ChatId, @from)"; . . You need to pass @from also.您还需要传递@from

You are inserting not updating the table.您插入的不是更新表。 So when you click the second time, it tries to insert the record with the same primary key into the table again.因此,当您第二次单击时,它会尝试再次将具有相同主键的记录插入到表中。 You cannot insert the same value for the primary key in the table more than once, it will be a primary key violation.您不能多次为表中的主键插入相同的值,这将违反主键。 The primary key is always unique.主键始终是唯一的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM