我使用SqlCommand从.sql文件执行脚本化查询。
我使用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();
答案 0 :(得分: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();
}
}
答案 1 :(得分:0)
如上所述,您可能不应该使用foreach
。出于兼容性原因,需要实现它,但这里的while (reader.Read())
循环更简单。也就是说,如果你愿意,你可以使用foreach
。 user
值实现IDataRecord
,您可以使用该接口访问值。
foreach (IDataRecord user in reader)
{
// access user[0], user["field"], etc. here
}