當我運行這個動作時,我收到了這條消息:「已經有一個打開的DataReader與這個Command相關聯,必須先關閉它。」一個開放的數據讀取器
我的代碼是:公共無效UpdatePoints(字符串rightScore,串rightWinner) {
cmd.CommandText = "select * from Users_Details";
cmd.Connection = connection;
connection.Open();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
int points=0;
string sql;
string hisScore = (string)rdr["lastbetscore"];
string hisWinner = (string)rdr["lastbetwinner"];
if (rightScore == hisScore)
points = points + 30;
if (rightWinner == hisWinner)
{
points = points + 20;
}
sql = "update Users_Details set lastgame_points='" + points + "', gamesplayed='" + ((int)rdr["gamesplayed"] + 1) + "',currentpoints='" + ((int)rdr["currentpoints"] + points) + "',pointsPG='" + (((int)rdr["currentpoints"] + points)/((int)rdr["gamesplayed"] + 1)) + "' where username='" + (string)rdr["username"] + "'";
cmd.CommandText = sql;
cmd.ExecuteScalar();
}
rdr.Close();
connection.Close();
}
我添加了它,但仍然收到錯誤消息 –
現在,它會打印出「已經有一個與此連接關聯的打開的DataReader,必須先關閉」。 ?而不是「命令」? –
我的第一個答案是錯誤的,因爲不僅可以重用命令,還可以重用連接。請查看更正的答案。 –