C# 如何在C中显示要标记的mySQL数据#
您好,我目前在用c#显示从mySQL数据库到标签的数据时遇到问题。嗯,在我的数据库中,我有6列,我想通过使用第6列限制第5列来调用特定数据。我的列名是count、fullname、position、year、course、partylist和numparty。为什么数据不能显示在标签上?谁能帮帮我吗C# 如何在C中显示要标记的mySQL数据#,c#,mysql,label,C#,Mysql,Label,您好,我目前在用c#显示从mySQL数据库到标签的数据时遇到问题。嗯,在我的数据库中,我有6列,我想通过使用第6列限制第5列来调用特定数据。我的列名是count、fullname、position、year、course、partylist和numparty。为什么数据不能显示在标签上?谁能帮帮我吗 string myConnection = "datasource=localhost;port=3307;username=root;password=root"; My
string myConnection = "datasource=localhost;port=3307;username=root;password=root";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand command = myConn.CreateCommand();
command.CommandText = "Select `Partylist` FROM expertsystem.addcandidate WHERE `NumParty`=1";
MySqlDataReader myReader;
try
{
myConn.Open();
myReader = command.ExecuteReader();
while (myReader.Read())
{
lblpartylist1.Text = myReader[5].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
myConn.Close();
问题:您仅从表中获取cloumn name
Partylist
,但您正在尝试访问第6列,该列不存在
解决方案1:您需要从表中获取所有列
替换此项:
Select `Partylist` FROM
lblpartylist1.Text = myReader[5].ToString();
为此:
Select * FROM
lblpartylist1.Text = myReader[0].ToString();
解决方案2:您需要将索引值从5更改为0
替换此项:
Select `Partylist` FROM
lblpartylist1.Text = myReader[5].ToString();
为此:
Select * FROM
lblpartylist1.Text = myReader[0].ToString();
解决方案3:
在执行命令之前,您没有将连接对象myConn
分配给命令对象command
试试这个:
try
{
myConn.Open();
command.Connection = myConn; //add this statement
myReader = command.ExecuteReader();
<强>建议:< /强>您的查询对SQL注入攻击开放。请考虑使用参数化的查询来避免它们。
< P> MyRe读器(5)的索引表示您的SELECT.索引。 你能试试这个吗string myConnection = "datasource=localhost;port=3307;username=root;password=root";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand command = myConn.CreateCommand();
command.CommandText = "Select Partylist FROM expertsystem.addcandidate WHERE NumParty=1";
MySqlDataReader myReader;
try
{
myConn.Open();
myReader = command.ExecuteReader();
while (myReader.Read())
{
lblpartylist1.Text = myReader[0].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
myConn.Close();
试着这样做,这就是我如何读取列来填充文本框的方式,当然,用数据库中所需列的真实名称替换列的名称
lblpartylist1.Text = myReader.GetString("Column_Name");
祝你好运谢谢!我试过你的建议,但仍然没有显示出我想要的。此外,我还调用了“Partylist”,因为我只需要特定的列。我在这里找不到真正的问题。我尝试了你的建议,遗憾的是,它仍然没有显示任何内容。如果有其他选项,请务必让我知道。@IamMe.:检查我的
解决方案3
,在执行命令之前,您没有将连接对象myConn
分配给您的命令对象命令。您也这样做了。这也没用。@Downvoter:你能解释一下这个问题吗?你能在catch中放置一个断点来显示执行是否没有引发异常。@IamMe或者你可以试试MessageBox.show(myReader.HasRows);在ExecuteReader之后显示查询是否返回row@lamMe. 你能试试前面评论的代码吗?