正如刚才提到的:
我正在使用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
吗?
我知道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的每个记录作为Int32
(int
)。如果表格列类型不是INT
,则需要更改此值。由于您只选择了一列(即"SELECT id"
),因此参数为0
,因为您获取的结果表仅包含一列。
此外,在您的代码中,您似乎希望将结果作为DataTable
获得;如果是这样,你应该使用MySqlDataAdapter
而不是MySqlDataReader
如下:
DataTable resultTable = new DataTable("ResultTable");
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
adapter.Fill(table);
更正你的sql命令
String sql_Command = @"SELECT id FROM orders.jsontest";