检查玩家是否存在错误

本文关键字:错误 存在 是否 玩家 检查 | 更新日期: 2023-09-27 18:14:13

我有这个windows窗体代码

private void StartGame_Click(object sender, EventArgs e)
{
    if (player.Text == "")
    {
        MessageBox.Show("Enter A player to proceed.");
    }
    else
    {
    //SQL Connection String
        using (SqlConnection conn = new SqlConnection("Data Source=Keith;Initial Catalog=SoftEngg;Integrated Security=True"))
        {
            conn.Open();
            bool exists = false;
            // create a command to check if the username exists
            using (SqlCommand cmd = new SqlCommand("select * from PlayerData where PlayerName = @player", conn))
            {
                cmd.Parameters.AddWithValue("player", player.Text);
                exists = (int)cmd.ExecuteScalar() > 0;
            }
            // if exists, show a message error
            if (exists)
                MessageBox.Show(player.Text, "is used by another user.");
            else
            {
                // does not exists, so, persist the user
                using (SqlCommand cmd = new SqlCommand("INSERT INTO PlayerData(PlayerName) values (@Playername)", conn))
                {
                    cmd.Parameters.AddWithValue("Playername", player.Text);
                    cmd.ExecuteNonQuery();
                }
            }
            conn.Close();
        }
    }
}

我的目标是提醒玩家并在系统中显示消息框"玩家已经存在"。但我的代码似乎不工作。当我运行程序时,我在这里的代码中得到一个错误:

exists = (int)cmd.ExecuteScalar() > 0;

,错误提示:(附加信息:对象引用未设置为对象的实例)

如何解决这个问题,请帮助

检查玩家是否存在错误

如果你想使用ExecuteScalar,你应该使用select Count(*) from PlayerData where PlayerName = @player

您的问题不在查询中。我的意思是不在这个select * from PlayerData where PlayerName = @player

你得到错误,因为exists = (int)cmd.ExecuteScalar() > 0;

: 这里您正在尝试将convert输出到Integer。因此,当cmd.ExecuteScalar()获得null的值在那个时候,你得到了错误。

Have to Remember

SqlCommand.ExecuteScalar:

执行查询,并返回中第一行的第一列查询返回的结果集。其他列或行为忽略。

你可以使用select * from PlayerData where PlayerName = @player,但是你必须确认这个表的第一列是NonNullable

和你的检查应该像

 exists = (cmd.ExecuteScalar()!=null)?true:false;

或者,您可以通过选择主键列来尝试。

select your_Primary_Key_Name from PlayerData where PlayerName = @player

 exists = (cmd.ExecuteScalar()!=null)?true:false;

不使用AddWithValue

cmd.Parameters.Add("@player",SqlDbType.Varchar,200).Value=YourValue;