本文介绍了将sql查询结果读入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从C#运行此查询,结果将是小于2000的1到20个整数之间的任意值,并将这些结果读入整数数组.我该怎么办?


I want to run this query from C# and the results will be anywhere from 1 to maybe 20 integers less than 2000, and read those results into an integer array. How do I do that?


Select DATEDIFF (DAY, DeployedDate, GETDATE())
From Deployment
Where EmployeeID =1
And
DeploymentID = 1";

推荐答案

SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING");

ArrayList valuesList = new ArrayList();


connection.Open();
//Read from the database
SqlCommand command = new SqlCommand("YOUR SQL QUERY HERE", connection);

SqlDataReader dataReader = command.ExecuteReader();

while (dataReader.Read())
{
    valuesList.Add(Convert.ToInt32(dataReader[0].ToString()));
}
connection.Close();



请注意,对于以上代码,将dataReader的索引替换为该列.想要获取第二列的值,请给它一个1.使用arraylist将所有内容都放入数组.



Note that for the above code, replace the index of dataReader with the column. Like to get the values of the second column give it a 1. Use an arraylist to get everything into an array.


using System.Linq;

var query = from deploy in dbContext.Deployment
            where deploy.EmployeeID == 1 && DeploymentID == 1
            select datediff(deploy.day, deploy.deployeddate, getdate());

return query.toarray();


foreach (DataRow row in dt.Rows) {
    string arrayItem = row[0];  // on every iteration you will be accessing it as an array item
}


这篇关于将sql查询结果读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:10
查看更多