2012-11-26 42 views
-1

我使用SqlCommand从.sql文件执行脚本查询。SqlCommand和ExecuteReader返回非公开成员

我用ExecuteReader得到结果。

但值是非公开成员,我无法访问它。

任何想法为什么以及如何解决这个问题?

代码

string root = AppDomain.CurrentDomain.BaseDirectory; 
string script = File.ReadAllText(root + @"..\SGBD\select_user_from_all_bases.sql"); 
string connectionString = @"Data Source=(local);Integrated Security=SSPI"; 
var conn = new SqlConnection(connectionString); 

conn.Open(); 

var users = new SqlCommand(script, conn).ExecuteReader(); 

foreach (var user in users) 
{ 

} 

conn.Close(); 

enter image description here

+0

你甚至看过你应该如何使用这个API? –

+0

如果你不想处理这个API的所有烦恼,可以考虑一些类似于“精灵”(在NuGet上搜索)的东西。整个工作是:'var users = conn.Query (script).ToList();' –

+0

@MarcGravell - 其实我想在json中公开这个用户,所以Dapper也许是我搜索的内容。谢谢。 –

回答

1

这是因为的ExecuteReader()返回一个SqlDataReader,没有条目。

Look at the documentation of the SqlDataReader to see how you should do

private static void ReadOrderData(string connectionString) 
{ 
    string queryString = 
     "SELECT OrderID, CustomerID FROM dbo.Orders;"; 

    using (SqlConnection connection = 
       new SqlConnection(connectionString)) 
    { 
     SqlCommand command = 
      new SqlCommand(queryString, connection); 
     connection.Open(); 

     SqlDataReader reader = command.ExecuteReader(); 

     // Call Read before accessing data. 
     while (reader.Read()) 
     { 
      Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1])); 
     } 

     // Call Close when done reading. 
     reader.Close(); 
    } 
} 
+2

注意:'command'和'reader'也应该有'using'语句。 –

+0

好吧,我试过,但读者[0]返回0,所以我认为它没有工作。其实这是一个好结果,我是一个白痴。谢谢。 –

0

前面已经提到的,你可能不应该使用foreach。出于兼容性的原因,它需要实施,但这里的while (reader.Read())循环更简单。也就是说,如果你愿意,你可以使用foreachuser值实现了IDataRecord,您可以使用该接口来访问这些值。

foreach (IDataRecord user in reader) 
{ 
    // access user[0], user["field"], etc. here 
}