[英]SqlCommand and ExecuteReader return Non-Public Members
I execute a scripted query from a .sql file with SqlCommand.我使用 SqlCommand 从 .sql 文件执行脚本查询。
I get the result with an ExecuteReader.我用 ExecuteReader 得到结果。
But values are as non-public member and I can't access it.但是值是非公共成员,我无法访问它。
Any idea why and how resolve that?知道为什么以及如何解决吗?
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();
This because ExecuteReader() returns a SqlDataReader, not the entries.这是因为 ExecuteReader() 返回一个 SqlDataReader,而不是条目。
Look at the documentation of the SqlDataReader to see how you should do : 查看 SqlDataReader 的文档,看看你应该怎么做:
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();
}
}
As mentioned already, you probably shouldn't be using foreach
.如前所述,您可能不应该使用foreach
。 For compatibility reasons, it needs to be implemented, but a while (reader.Read())
loop is simpler here.出于兼容性原因,需要实现,但是这里一个while (reader.Read())
循环更简单。 That said, you can use foreach
anyway if you want.也就是说,如果您愿意,无论如何都可以使用foreach
。 The user
values implement IDataRecord
, and you can use that interface to access the values. user
值实现IDataRecord
,您可以使用该接口访问这些值。
foreach (IDataRecord user in reader)
{
// access user[0], user["field"], etc. here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.