[英]Inserting a row into a sql table in c# with autoincrement primary key
當ID列為主鍵並設置為自動增量時,如何執行表插入命令?
我嘗試了以下方法:
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();
}
但是無論將什么值輸入ID(我嘗試過0和-1),它都會在ID列下創建一個具有該值的新行。 結果,當我嘗試插入下一行時,由於現在我有兩個具有相同ID的行,因此給我一個錯誤。
如果該列是自動增量列,則無需提及。
string commtext = @"Insert INTO table1 (Username) SELECT @User";
SqlCommand comm = new SqlCommand(commtext, conn);
comm.Parameters.AddWithValue("@User", loggedinuser);
您說出這樣的話:
int addUser( string userName )
{
if ( string.IsNullOrWhiteSpace(userName) throw new ArgumentException("invalid user name" , "userName") ;
int user_id ;
string connectString = GetSomeConnectString() ;
using ( SqlConnection connection = new SqlConnection( connectString ) )
using ( SqlCommand cmd = connection.CreateCommand() )
{
cmd.CommandType = CommandType.Text ;
cmd.CommandText = @"
insert dbo.user ( user_name ) values ( @user_Name )
select user_id = @@SCOPE_IDENTITY
" ;
cmd.Parameters.AddWithValue( "@user_name" , userName ) ;
connection.Open() ;
user_id = (int) cmd.ExecuteScalar() ;
connection.Close() ;
}
return user_id ;
}
不能在插入內容中指定具有identity
屬性的任何列(或自動遞增列)。 您必須指定要提供其值的列。 任何未提供的列都必須為可為空,具有默認約束或為自動遞增列。
除非您要明確設置ID,否則不要將IDENTITY_INSERT設置為ON,否則請使用自動遞增的值。
using (SqlConnection conn = new SqlConnection(connstring))
{
conn.Open();
string commtext = @"Insert INTO table1 (Username)
SELECT @User";
SqlCommand comm = new SqlCommand(commtext, conn);
comm.Parameters.AddWithValue("@User", loggedinuser);
identChange.ExecuteNonQuery();
comm.ExecuteNonQuery();
conn.Close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.