如何在C#中显示mySQL数据标签

时间:2014-03-18 17:03:37

标签: c# mysql label

您好,我目前在将mySQL数据库中的数据显示到c#中的标签时遇到问题。好吧,在我的数据库中,我有6列,我想通过使用第6列限制来调用第5列中的特定数据。我的列名是count,fullname,position,year,course,partylist和numparty。为什么数据不能显示在标签上?有人可以帮助我。

 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();

3 个答案:

答案 0 :(得分:1)

myReader [5]的索引代表你选择的索引。

你可以试试这个:

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();

答案 1 :(得分:0)

问题:您只是从表中获取cloumn名称Partylist,但是您正在尝试访问第6列,而不是那里。

解决方案1:您需要从表中获取所有列。

替换它:

 Select `Partylist` FROM 

有了这个:

 Select * FROM 

解决方案2:您需要将索引值从5更改为0.

替换它:

 lblpartylist1.Text = myReader[5].ToString();

有了这个:

 lblpartylist1.Text = myReader[0].ToString();

解决方案3:

在执行命令之前,您没有将Connection对象myConn分配给命令对象command

试试这个:

try
{
  myConn.Open();
  command.Connection = myConn;  //add this statement
  myReader = command.ExecuteReader();

建议:您的查询对sql注入攻击是开放的,请考虑使用参数化查询来避免它们。

答案 2 :(得分:0)

尝试这样做,这就是我读取列填充文本框的方法。当然,将Column_Name替换为数据库中所需列的真实名称。

lblpartylist1.Text = myReader.GetString("Column_Name");
祝你好运