我试图让服务器从 SQL 数据库中读取 int 'rank',但是我得到“使用未分配的局部变量”,因为它不会读取 'rank',直到它应该在 while 语句中设置,但是我无法将其移出,因为它在进入 try and catch 之前不会执行 SQL 查询。
特别是这里:
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
rank = rdr.GetInt32("rank");
}
完整代码:
class Ban : ICommand
{
public string Command { get { return "ban"; } }
public int RequiredRank { get { return 3; } }
public void Execute(Player player, string[] args)
{
int rank;
string name = "'" + args[0] + "'";
if (args.Length == 0)
{
player.SendHelp("Usage: /ban <username>");
}
try
{
using (Database dbx = new Database())
{
var cmd = dbx.CreateQuery();
cmd.CommandText = "SELECT rank FROM accounts where name=@name";
cmd.Parameters.AddWithValue("@name", name);
cmd.ExecuteNonQuery();
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
rank = rdr.GetInt32("rank");
}
Console.Write("{0} ({1}) tried to ban {2}({3})", player.Name, player.Client.Account.Rank, name, rank);
if (rank < player.Client.Account.Rank)
{
var cmda = dbx.CreateQuery();
cmda.CommandText = "UPDATE accounts SET banned=1, rank=0 WHERE name=@name";
cmda.Parameters.AddWithValue("@name", args[0]);
if (cmda.ExecuteNonQuery() == 0)
{
player.SendInfo("Could not ban");
}
else
{
foreach (var i in player.Owner.Players)
{
if (i.Value.nName.ToLower() == args[0].ToLower().Trim())
{
i.Value.Client.Disconnect();
player.SendInfo("Account successfully Banned");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Out.WriteLine(args[0] + " was Banned.");
Console.ForegroundColor = ConsoleColor.White;
}
}
}
}
else if (rank >= player.Client.Account.Rank)
player.SendInfo("Could not ban");
}
}
catch
{
player.SendInfo("Could not ban");
}
}
}