我还很新,我正在从事一个项目,但是我无法获取它来显示数据或找出问题所在或做错了什么。任何帮助都是极好的。就像我说的那样,我还很新,但仍在继续前进。

public class loadData
{
    public int ID { get; set; }
    public string LOAD1 { get; set; }
    public string LOAD2{ get; set; }
    public string LOAD3 { get; set; }
    public string LOAD4 { get; set; }
    public string constructString { get; set; }

    public List<loadData> Select()
    {
        const string query = "SELECT * FROM data.dataload";
        string constring = constructString;

        //Create a list to store the result
        var list = new List<loadData>();

        //Open connection

        //Create Command
        MySqlConnection conDatabase = new MySqlConnection(constring);
        try
        {
            using (MySqlCommand cmdDatabase = new MySqlCommand(query, conDatabase))
            {
                //Create a data reader and Execute the command
                MySqlDataReader dataReader = cmdDatabase.ExecuteReader();

                //Read the data and store them in the list
                while (dataReader.Read())
                {
                    list.Add(new loadData
                    {
                        ID = int.Parse(dataReader["ID"].ToString()),
                        LOAD1 = dataReader["LOAD1"].ToString(),
                        LOAD2 = dataReader["LOAD2"].ToString(),
                        LOAD3 = dataReader["LOAD3"].ToString(),
                        LOAD4 = dataReader["LOAD4"].ToString(),
                    });
                }

                Console.ReadLine();

                //close Data Reader
                dataReader.Close();

                //close Connection
                conDatabase.Close();

                //return list to be displayed
                return list;
            }
        }
        catch
        {
            return list;
        }
        finally { conDatabase.Close(); }

    }

    public void Display(List<loadData> list)
    {
        foreach (var load in list)
        {
            Console.WriteLine(string.Format("{0} {1}:\n{2}\n{3}\n{4}\n",
                load.ID,
                load.LOAD1,
                load.LOAD2,
                load.LOAD3,
                load.LOAD4));
        }
    }
    /// CALL
    //MYSQL
    loadData data = new loadData();
    data.constructString = "datasource=dbt;port=8888;username=UNAME;password=PW;";
    data.Display(data.Select());
}


(根据OP的评论),错误为:


  {“连接必须有效且打开。”}发生类型为'System.InvalidOperationException'的未处理异常

最佳答案

您忘记了呼叫conDatabase.Open()。在尝试执行cmdDatabase.ExecuteReader();之前执行此操作,您会没事的

关于c# - C#MySQL表列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41098997/

10-09 00:37