gpt4 book ai didi

c# - 错误: You have specified an invalid column ordinal

转载 作者:行者123 更新时间:2023-11-29 08:16:23 36 4
gpt4 key购买 nike

我在将数据从数据库加载到 Windows 窗体时遇到问题。我使用下面的代码通过数据读取器检索信息,然后将检索到的信息设置到适当的标签和图片框,但是当显示 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";
}
}
}
}
}

最佳答案

列序号以 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

Gets the value of the specified column as a String object.

Parameters: The zero-based column ordinal.

Returns: The value of the specified column.

编辑:

您需要通读 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";
}
}
}

关于c# - 错误: You have specified an invalid column ordinal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20527527/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com