C# 如何使用MySqlDataReader从数据库中检索值?
通过使用此代码,我希望从DB中检索表中的一些行: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
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());
}