-3

ionline - 类,字符串 myname

private static void SetOnlineStatus(PacketHeader header, Connection connection, ionline message)
    {
        Console.WriteLine("Check online: " + message.myname);
        MySqlCommand mycmd = new MySqlCommand();
        mycmd.CommandText = "SELECT * FROM users WHERE username = ?user";
        mycmd.Connection = mconnection;
        mycmd.Parameters.AddWithValue("user", message.myname);
        MySqlDataReader Reader = mycmd.ExecuteReader();

        while (Reader.Read())
        {
            Console.WriteLine("Check online: " + message.myname+" "+GetDBString("username",Reader));
            MySqlCommand mycmd2 = new MySqlCommand();
            mycmd2.CommandText = "UPDATE users SET online = 0 WHERE userid = @user2";
            mycmd2.Parameters.AddWithValue("@user2", Reader.GetInt32("userid"));
            mycmd2.Connection = mconnection;
            Console.WriteLine(mycmd2.ExecuteNonQuery().ToString());
        }


    }

Mysql 请求“mycmd2”未执行。我的查询中有什么不正确的?

4

1 回答 1

1

当 DataReader 打开时,它的连接正忙于为阅读器服务。
该连接不能用于对数据库进行其他操作。
你应该得到一个例外。

如果您的第一个查询返回零或一行,那么您可以使用 ExecuteScalar 方法简化代码并消除使用 MySqlDataReader 的需要

    Console.WriteLine("Check online: " + message.myname);
    MySqlCommand mycmd = new MySqlCommand();
    mycmd.CommandText = "SELECT userid FROM users WHERE username = ?user";
    mycmd.Connection = mconnection;
    mycmd.Parameters.AddWithValue("user", message.myname);
    object result = mycmd.ExecuteScalar();
    if(result != null)
    {
        int userID = Convert.ToInt32(result);
        MySqlCommand mycmd2 = new MySqlCommand();
        mycmd2.CommandText = "UPDATE users SET online = 0 WHERE userid = @user2";
        mycmd2.Parameters.AddWithValue("@user2", userID);
        mycmd2.Connection = mconnection;
        mycmd2.ExecuteNonQuery();
    }
于 2013-06-20T20:36:04.550 回答