How to insert value into primary key identity column in SQL through C#?

前端 未结 4 1130
花落未央
花落未央 2021-01-17 05:46

(My problem solved. As almost everyone said I had to remove @OB_ID and left it to SQL to assign value.)

I want to insert a new record into a table in SQL database th

4条回答
  •  日久生厌
    2021-01-17 06:24

    You don't need to add anything as SQL Server will automatically increment and assign the Identity field. So, simply remove @OB_ID and SQL Server will know to add the next key in sequence, so...

    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);
            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();
    

提交回复
热议问题