将sql查询结果读入数组 [英] read sql query results into an array

查看:690
本文介绍了将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";

推荐答案

您可以在以下步骤中使用ADO .NET:

1.形成一个连接字符串.
2.形成您的查询
3.添加参数
4.在DataReader的帮助下执行查询

这两篇文章将为您提供帮助:

为初学者使用ADO.NET [ ADO.NET OleDbDataReader类 [
You can make use of ADO .NET in the following steps:

1. Form a connection string.
2. Form your query
3. Add parameters
4. Execute the query with the help of DataReader

These two articles will help you:

Using ADO.NET for beginners[^]

The ADO.NET OleDbDataReader class[^]


You can get values like this:

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.


如果您的代码库在C#3.0及更高版本中,则LInQ会帮助您

If your code base is in C# 3.0 and above, LInQ helps

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();


您可以为此目的使用DataTable. (由于您只有一列,因此)

1.使用DataAdapter
填充DataTable 2.现在,您可以像这样访问它:

这里的``dt''是由DataAdapter填充的DatTable:

You can use DataTable for this purpose. ( since you have only one column, as a result)

1. Fill DataTable, using DataAdapter
2. Now you can access it like this:

Here ''dt'' is DatTable filled by DataAdapter:

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


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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆