gpt4 book ai didi

C# MySQL 表列表

转载 作者:行者123 更新时间:2023-11-29 11:07:53 25 4
gpt4 key购买 nike

我是个新手,正在开发一个项目,但是我无法让它显示数据或找出问题所在或我做错了什么。任何帮助都是极好的。正如我所说,我是个新手,而且仍在经历这个过程。

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给出的评论),错误是:

{"Connection must be valid and open."} An unhandled exception of type 'System.InvalidOperationException' occurred

最佳答案

您忘记调用conDatabase.Open()。在尝试执行 cmd Database.ExecuteReader(); 之前执行此操作,就可以了

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

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