Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用MySqlDataReader从数据库中检索值?_C#_Mysql_.net - Fatal编程技术网

C# 如何使用MySqlDataReader从数据库中检索值?

C# 如何使用MySqlDataReader从数据库中检索值?,c#,mysql,.net,C#,Mysql,.net,通过使用此代码,我希望从DB中检索表中的一些行: ID int ParentID int? IsVisible bool 差不多 while(myReader.Read()) { ID = AsInteger(myReader["ID"]).Value; Parent = AsInteger(myReader["Parent"]); IsVisble = AsBoolean(myReader["IsVisible"]); } 作为。。。帮助器函数可能类似于 private static

通过使用此代码,我希望从DB中检索表中的一些行:

ID int
ParentID int?
IsVisible bool

差不多

while(myReader.Read()) 
{
ID = AsInteger(myReader["ID"]).Value;
Parent = AsInteger(myReader["Parent"]);
IsVisble = AsBoolean(myReader["IsVisible"]);
}
作为。。。帮助器函数可能类似于

private static int? AsInteger(Object argValue)
{
   if ((argValue == null) || (argValue == DBNull.Value))
   {
     return null;
   }
   return Convert.ToInt(argValue);
}

在泛泛的静态helper类中处理所有helper方法通常是很容易的,除非您真的在一个类中完成所有这一切

注意DBNull,它不是null:(

以及字节为[]的BLOB如果它们不是DBNull。我也没有这样做,但MySql的一些有趣类型,如日期和时间,可能会引起眉头紧锁,枚举看起来像是一个字符串。我记得的是,不久前的一次调查表明,是否将MySql作为我们产品的后端,作为sql server的替代品

您还可以使用索引访问结果的列

e、 g.myReader[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());   
}
if(myReader.Read())
{
StringBuilder sb=新的StringBuilder(myReader.FieldCount);

对于(int i=0;ihmm,如果我尝试获取
myReader[“ParentID”]
然后我得到一个异常
在results:ParentID中找不到指定的列
,即使我想从表
中获取
select*。当然,该列存在于该表中,从这里无法确定,但如果无法找到,则会发生一些有趣的事情。您也可以作为数组访问结果,如在myReader[0]中一样,所以你可以做一个foreach并列出它们,看看是什么。如果我想运行循环
foreach(myReader中的var项){}
,它被调用了4次(这是正确的),但是编译器没有进入这个循环,我会给出一点答案
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());   
}