Inserting a row into a sql table in c # with the primary key auto_increment

How do I execute a table insert command when the ID column is the primary key and set to autoincrement?

I’ve tried the following:

using (SqlConnection conn = new SqlConnection(connstring))
        {
            SqlCommand identChange = conn.CreateCommand();
            identChange.CommandText = "SET IDENTITY_INSERT table1 ON";
            conn.Open();
            string commtext = @"Insert INTO table1 (ID, Username)
                       SELECT @ID, @User";
            SqlCommand comm = new SqlCommand(commtext, conn);
            comm.Parameters.AddWithValue("@ID", -1);
            comm.Parameters.AddWithValue("@User", loggedinuser);
            identChange.ExecuteNonQuery();
            comm.ExecuteNonQuery();
            conn.Close();
        }

but regardless of what value is put into ID (i’ve tried 0 and -1), it creates a new row with that value under the ID column. As a result, when I try to insert the next row, it gives me an error since now I have two rows with the same ID.

You just don’t have to mention the column if it is a autoincrement column.

string commtext = @"Insert INTO table1 (Username) SELECT @User";
SqlCommand comm = new SqlCommand(commtext, conn);
comm.Parameters.AddWithValue("@User", loggedinuser);
Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 后端存储 » Inserting a row into a sql table in c # with the primary key auto_increment

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录