我是 C# 的初学者。我尝试从更新查询中获取最后插入的 id。但我得到一个错误这是我的代码
String Query1 = "insert into test(userid,score) values ('"+userid+"',0);";
SqlConnection conn1 = new SqlConnection(constring);
SqlCommand cmdDatabase1 = new SqlCommand(Query1, conn1);
SqlDataReader dbreader1;
conn1.Open();
testid = (int)cmdDatabase1.ExecuteScalar();
dbreader1 = cmdDatabase1.ExecuteReader();
while (dbreader1.Read())
{
}
我得到这个错误。
你调用的对象是空的。在这一行 testid = (int)cmdDatabase1.ExecuteScalar();
我也试过这个
String Query1 = "insert into test(userid,score) values ('"+userid+"',0);";
SqlConnection conn1 = new SqlConnection(constring);
SqlCommand cmdDatabase1 = new SqlCommand(Query1, conn1);
SqlDataReader dbreader1;
conn1.Open();
object count = cmdDatabase1.ExecuteScalar();
System.Diagnostics.Trace.WriteLine(count.GetType());
int testid = (int)count;
dbreader1 = cmdDatabase1.ExecuteReader();
while (dbreader1.Read())
{
}
同样的错误Object reference not set to an instance of an object.
在这一行 System.Diagnostics.Trace.WriteLine(count.GetType());