如何生成List< String>从SQL查询?
问题描述:
如果我定义了DbCommand
来执行类似的操作:
If I have a DbCommand
defined to execute something like:
SELECT Column1 FROM Table1
生成返回记录的List<String>
的最佳方法是什么?
What is the best way to generate a List<String>
of the returned records?
没有像我正在使用VS2005的Linq等.
No Linq etc. as I am using VS2005.
答
我认为这就是您想要的.
I think this is what you're looking for.
List<String> columnData = new List<String>();
using(SqlConnection connection = new SqlConnection("conn_string"))
{
connection.Open();
string query = "SELECT Column1 FROM Table1";
using(SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
columnData.Add(reader.GetString(0));
}
}
}
}
未经测试,但这应该可以正常工作.
Not tested, but this should work fine.