C# DbDataRecord中使用什么方法来验证列是否存在?
我想验证该字段是否真的存在于数据库的表中。我已经使用SqlDataReader类来读取数据。在将值分配给SqlDataReader之后,我使用foreach创建了一个循环来迭代每条记录。下面是示例代码C# DbDataRecord中使用什么方法来验证列是否存在?,c#,.net-3.5,C#,.net 3.5,我想验证该字段是否真的存在于数据库的表中。我已经使用SqlDataReader类来读取数据。在将值分配给SqlDataReader之后,我使用foreach创建了一个循环来迭代每条记录。下面是示例代码 SqlCommand sqlCommand = new SqlCommand(); SqlDataReader sqlDr = sqlCommand.ExecuteReader(); Foreach(DbDataRecord record in sqlDr) { // Validate
SqlCommand sqlCommand = new SqlCommand();
SqlDataReader sqlDr = sqlCommand.ExecuteReader();
Foreach(DbDataRecord record in sqlDr)
{
// Validate if the value is not null and (I want to validate if this field really exist in the table)
if(record["MyField1"].GetType().ToString() == "System.DBNull")
{
// Statement here
}
}
我希望得到一个善意的回答。非常感谢。保持代码与您的问题类似,您可以这样做:
using (SqlCommand sqlCommand = new SqlCommand())
{
SqlDataReader sqlDr = sqlCommand.ExecuteReader();
if (!sqlDr.Read()) return;
HashSet<string> fieldNames = new HashSet<string>(sqlDr.FieldCount);
for (int i = 0; i < sqlDr.FieldCount; i++)
{
fieldNames.Add(sqlDr.GetName(i));
}
if (!fieldNames.Contains("MyField1") || !fieldNames.Contains("MyField2"))
{
// do something here
}
}
使用(SqlCommand SqlCommand=new SqlCommand())
{
SqlDataReader sqlDr=sqlCommand.ExecuteReader();
如果(!sqlDr.Read())返回;
HashSet fieldNames=新的HashSet(sqlDr.FieldCount);
对于(int i=0;i
我将编写一个扩展
方法,该方法迭代读卡器中的每个字段并返回true/false
public static class DataRecordExtensions
{
public static bool HasColumn(this IDataRecord dr, string columnName)
{
for (int i = 0; i < dr.FieldCount; i++)
{
if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
return true;
}
return false;
}
}
我在找这个,非常感谢…:(就我而言,我不能使用like扩展,因为我在框架1.1中.)
if (objReader.HasColumn("FirstName")
{
//Column exist. So lets read the value
someobject.Name= objReader.GetString(objReader.GetOrdinal("FirstName"));
}