在C#中的标签中显示mySql表

时间:2014-07-03 04:57:15

标签: c# mysql sql stringbuilder dataview

我试图实现一个与mysql数据库结合的应用程序。我想在终端视图中显示 table1 ,而不是在数据网格视图中显示它。我使用下面的代码连接并显示MySql数据库:

string myConnection = "datasource=localhost;port=3306;username=root;password=";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand command = myConn.CreateCommand();
command.CommandText = "Select * FROM database_name.table1";
MySqlDataReader myReader;

        try
        {
            myConn.Open();
            myReader = command.ExecuteReader();

            while (myReader.Read())
            {
                label1.Text = myReader[0].ToString();

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        myConn.Close();

此代码仅执行表的最后一个值。但是,我想显示整个表格,我希望它在标签中显示。所以我可以像终端视图一样设计它。

对此的任何帮助都会很棒。

感谢高级!

1 个答案:

答案 0 :(得分:1)

我认为MySqlDataReader.FieldCount Property会很有用。

试试这段代码:

string myConnection = "datasource=localhost;port=3306;username=root;password=";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand command = myConn.CreateCommand();
command.CommandText = "Select * FROM database_name.table1";
MySqlDataReader myReader;

    try
    {
        myConn.Open();
        myReader = command.ExecuteReader();

        while (myReader.Read())
        {
            if(label1.Text.Length > 0)
                 label1.Text += Environment.NewLine;

            for(int i=0; i<myReader.FieldCount; i++)
                label1.Text += myReader[i].ToString() + "    ";
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    myConn.Close();

注意:建议usingmysqlconnectionmysqldatareader使用mysqlcommand声明。

更新(根据jmcilhinney的建议使用StringBuilder):

// Method used to retrieve data from DB
string GetFormattedText()
{
    string myConnection = "datasource=localhost;port=3306;username=root;password=";            

    using (MySqlConnection myConn = new MySqlConnection(myConnection))
    {
        myConn.Open();

        using (MySqlCommand command = myConn.CreateCommand())
        {
            command.CommandText = "Select * FROM database_name.table1";

            using (MySqlDataReader myReader = command.ExecuteReader())
            {
               try
               {
                   StringBuilder sb = new StringBuilder();

                   while (myReader.Read())
                   {
                       if (sb.Length > 0)
                           sb.Append(Environment.NewLine);

                        for (int i = 0; i < myReader.FieldCount; i++)
                           sb.AppendFormat("{0}    ", myReader[i]);                               
                    }

                    return sb.ToString();
               }
               catch (Exception ex)
               {
                    MessageBox.Show(ex.Message);
               }
            }
        }
    }

    return string.Empty;
}

<强>用法

 label1.Text = GetFormattedText();