检查播放器是否存在错误

时间:2015-09-22 16:51:46

标签: c# sql-server database winforms

我有这个窗体表格代码

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;

并且错误说明:(附加信息:对象引用未设置为对象的实例。)

如何解决此问题,请帮助。

2 个答案:

答案 0 :(得分:3)

如果您想使用select Count(*) from PlayerData where PlayerName = @player

,则应使用ExecuteScalar

答案 1 :(得分:2)

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

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

,您收到了错误消息

<强>原因: 在这里,您尝试convert输出到Integer。 因此,当cmd.ExecuteScalar()获得null值时,您就会收到错误。

必须记住

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;
  

do not use AddWithValue

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