通过使用此代码,我想从数据库中检索表中的一些行:
ID int
ParentID int?
IsVisible bool
MySqlCommand myCommand = new MySqlCommand(mySelectQuery, myConnection);
myConnection.Open();
MySqlDataReader myReader = myCommand.ExecuteReader();
try
{
while(myReader.Read())
{
//here I want to retrieve the all returned data
}
}
finally
{
myReader.Close();
myConnection.Close();
}
最佳答案
有点像
while(myReader.Read())
{
ID = AsInteger(myReader["ID"]).Value;
Parent = AsInteger(myReader["Parent"]);
IsVisble = AsBoolean(myReader["IsVisible"]);
}
Where As... are helper functions 可能像
private static int? AsInteger(Object argValue)
{
if ((argValue == null) || (argValue == DBNull.Value))
{
return null;
}
return Convert.ToInt(argValue);
}
等等
在无处不在的静态帮助程序类中使用所有的帮助程序方法通常很麻烦,除非您打算在一个类中完成所有这些工作。
注意 DBNull,它不是空的。 :(
如果 Blob 不是 DBNull,则它们是 byte[]。也没有做过,但 MySql 的一些有趣类型(如 Date 和 Time)可能会引起皱眉,而枚举作为一个字符串出现,我似乎记得。我记得的是前段时间的一个调查,是否将 MySQl 作为我们其中一个产品的后端,作为 sql server 的替代品。
您还可以使用索引访问结果的列
例如我的读者[0].
类上有很多方法,GetValues 返回一个基于当前行的对象数组。
这也能派上用场
if (myReader.Read())
{
StringBuilder sb = new StringBuilder(myReader.FieldCount);
for(int i = 0; i<myReader.FieldCount; i++)
{
sb.AppendLine(myReader.GetName(i);
}
Console.Write(sb.ToString());
}
关于c# - 如何使用 MySqlDataReader 从数据库中检索值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9320425/