我有这个代码:
string insertSql =
"INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(@UserId, @GameId)";
using (SqlConnection myConnection = new SqlConnection(myConnectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
myCommand.Parameters.AddWithValue("@UserId", newUserId);
myCommand.Parameters.AddWithValue("@GameId", newGameId);
myCommand.ExecuteNonQuery();
myConnection.Close();
}
Run Code Online (Sandbox Code Playgroud)
当我插入这个表时,我有一个auto_increment int主键列调用GamesProfileId,如何在此之后获取最后一个插入的列,以便我可以使用该id插入另一个表?
我正在使用SqlCommand对象将记录插入到具有自动生成主键的表中.当我使用ExecuteScalar()方法时,如何编写命令文本以便获取新创建的ID?
我很难获得最后插入的字段
selct scope identity();
SELECT *
FROM Person
ORDER BY PersonID DESC
LIMIT 1
Run Code Online (Sandbox Code Playgroud) 我正在使用SqlCommand这样的:
command.CommandText = "INSERT INTO ... VALUES ...; SELECT SCOPE_IDENTITY();";
Run Code Online (Sandbox Code Playgroud)
这样就够了,还是我需要BEGIN TRAN等等?(这里提到.)
当然,我先尝试过,它运行正常.但即使有两个同时插入,它还能正常工作吗?(而且我不确定如何测试它.)