1

I am using the following code in order to insert some data into my SQL Server table. 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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Javad-M
  • 456
  • 6
  • 22

1 Answers1

0

It should be string sqlTxt1 = "INSERT INTO Users (ChatId , UserName) VALUES (@ChatId, @from)";. You need to pass @from also.

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.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197