如何使用C#连接到mysql并获取json数据?

问题描述 投票:1回答:2

正如刚才提到的:

我正在使用C#连接到MySQL数据库,我想阅读JSON数据类型。我使用MySqlCommand.ExecuteReader方法:

using (MySqlConnection sconn = new MySqlConnection(sqlConnectString))  
{      
    sconn.Open(); 
    String sql_Command = @"SELECT `id` FROM  orders.jsontest;"; 

    using (MySqlCommand scmd = new MySqlCommand(sql_Command, sconn))
    {
        **MySqlDataReader sdr = scmd.ExecuteReader();**  // fatal error
        DataTable datatable = new DataTable();

        // ...
    }
}

难道我不能在这里使用ExecuteReader吗?

c# mysql json
2个回答
0
投票

我知道this question is old,但是如果您还没有解决问题或其他任何人遇到类似问题,以下代码应该适合您:

private IEnumerable<int> GetIds()
{
    using (MySqlConnection connection = new MySqlConnection(connectionString))
    {
        connection.Open();
        string commandText = @"SELECT id FROM jsontest"; // Assuming that `orders` is your database, then you do not need to specify it here.

        using (MySqlCommand command = new MySqlCommand(commandText, connection))
        {
            MySqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                yield return reader.GetInt32(0);
            }
        }
    }
}

现在你应该注意的是这条线

while (reader.Read())

只要jsontest仍能读取有效结果并且此行,它会从MySqlDataReader表中获取结果

yield return reader.GetInt32(0);

它指示reader获取并返回所获取的表one at a time的每个记录作为Int32int)。如果表格列类型不是INT,则需要更改此值。由于您只选择了一列(即"SELECT id"),因此参数为0,因为您获取的结果表仅包含一列。

此外,在您的代码中,您似乎希望将结果作为DataTable获得;如果是这样,你应该使用MySqlDataAdapter而不是MySqlDataReader如下:

DataTable resultTable = new DataTable("ResultTable");
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
adapter.Fill(table);

0
投票

更正你的sql命令

String sql_Command = @"SELECT id FROM  orders.jsontest";
© www.soinside.com 2019 - 2024. All rights reserved.