错误:您指定了无效的列序号

时间:2013-12-11 18:50:36

标签: c# mysql database winforms sqldatareader

我在将数据从我的数据库加载到Windows窗体时出现问题。我正在使用下面的代码通过datareader检索信息,然后将检索到的信息设置为适当的标签和图片框,但是当显示AirSpace表单时,我会在标题中获得异常。我对此进行了一些研究并得出结论,当应用程序试图访问边界之外的序数但在本例中无效时我会给出此异常(我不认为)。

如果您需要任何进一步的解释或详细信息,请询问。提前谢谢。

代码:

private void AirSpace_Shown(object sender, EventArgs e)
    {
        string connectionString = "datasource=localhost;port=3306;username=********;password=********";
        Login login = new Login();
        using (MySqlConnection conn = new MySqlConnection(connectionString))
        {
            using (MySqlCommand cmd = conn.CreateCommand())
            {
                string select = "SELECT username, premium, picture FROM userinfo.users WHERE username = @username;";
                //                        (0)       (1)      (2)
                conn.Open();
                cmd.CommandText = select;
                cmd.Parameters.AddWithValue("@username", login.UsernameTextBox.Text);
                using (MySqlDataReader Reader = cmd.ExecuteReader())
                {
                        While(Reader.read())
                        {
                        //Set the user's profile picture to the user's profile picture.
                        ProfilePicture.Load(Reader.GetString(2));
                        //Set the username to the user's username
                        Username.Text = Reader.GetString(0);
                        //Set the app version to the user's version
                        if (Reader.GetString(1) == "1")
                        {
                            AppVersionLabel.Text = "Premium";
                        }
                        else
                        {
                            AppVersionLabel.Text = "Free";
                        }
                     }
                }
            }
        }

1 个答案:

答案 0 :(得分:2)

列oridnals以0而不是1

开头
string select = "SELECT username, premium, picture FROM userinfo.users WHERE username = @username;";
 //                        (0)       (1)      (2)

以下一行

ProfilePicture.Load(Reader.GetString(3));

应该是:

ProfilePicture.Load(Reader.GetString(2));

请参阅:25.2.3.5. MySqlDataReader

  

<强> 25.2.3.5.5。 GetString的

     

以String对象的形式获取指定列的值。

     

参数:从零开始列序号。

     

返回:指定列的值。

编辑:

您需要通读DataReader,如:

using (MySqlDataReader Reader = cmd.ExecuteReader())
{
    while (Reader.Read())
    {
        //Set the user's profile picture to the user's profile picture.
        ProfilePicture.Load(Reader.GetString(2));
        //Set the username to the user's username
        Username.Text = Reader.GetString(0);
        //Set the app version to the user's version
        if (Reader.GetString(1) == "1")
        {
            AppVersionLabel.Text = "Premium";
        }
        else
        {
            AppVersionLabel.Text = "Free";
        }
    }
}