gpt4 book ai didi

mysql - IEnumerable 从 mySQL 连接打印出单个实体

转载 作者:行者123 更新时间:2023-11-30 22:11:15 24 4
gpt4 key购买 nike

首先,我是这方面的新手,所以请多多包涵。

所以,我想从 xCode 的 Web 服务中获取数据。因此,我正在构建一个 web 服务,它可以在 mySql 中获取数据并以 json 格式呈现它们(当我完成时)。

但是,现在,我离...我已经建立了我的数据库,它在服务器上。

我在我的 web.config 中创建了连接字符串,我在下面的代码中尝试建立连接,尝试获取并显示 ID = 1 的行。因此我希望它显示所有我的数据库中的实体,但这是一个很好的开始。

我认为我的连接没问题,(不知道如何测试它,除了让它从我的页面上的数据库中打印一些东西)

但是,我的代码出现错误

cannot implicitly convert type string to 'system.collections.generic.ienumerable<string>'

你可能会说它的一个错误解决了 stackoverflow 上的另一个地方,但尽管如此我似乎还是无法理解如何解决它。

        MySql.Data.MySqlClient.MySqlConnection mySqlConnection;
MySql.Data.MySqlClient.MySqlCommand cmd;
String queryStr;

public IEnumerable<String> Get()
{

String connString = System.Configuration.ConfigurationManager.ConnectionStrings["MySql"].ToString();
mySqlConnection = new MySql.Data.MySqlClient.MySqlConnection(connString);

mySqlConnection.Open();
queryStr = "SELECT * FROM `CustomerDb` WHERE 'ID' = '1'";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, mySqlConnection);
cmd.ExecuteReader();
mySqlConnection.Close();

return queryStr;
}

非常感谢您。

更新

我已经为我的数据库实体制作了这些构造函数

    public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Category { get; set; }

最佳答案

问题是您试图返回一个字符串,其中函数 Get() 的返回类型是 IEnumerable。我想您需要获取从表中选择的内容而不是查询字符串,对吗?

MySql.Data.MySqlClient.MySqlConnection mySqlConnection;
MySql.Data.MySqlClient.MySqlCommand cmd;
String queryStr;

public IEnumerable<String> Get()
{

String connString = System.Configuration.ConfigurationManager.ConnectionStrings["MySql"].ToString();
mySqlConnection = new MySql.Data.MySqlClient.MySqlConnection(connString);

mySqlConnection.Open();
queryStr = "SELECT * FROM `CustomerDb` WHERE 'ID' = '1'";
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, mySqlConnection);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
yield return reader["Name"]; // Assume you want name in your result.
}

mySqlConnection.Close();

}

关于mysql - IEnumerable 从 mySQL 连接打印出单个实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40061437/

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