如何保存选择SQL查询结果在C#Asp.net数组 [英] How to save SELECT sql query results in an array in C# Asp.net

查看:99
本文介绍了如何保存选择SQL查询结果在C#Asp.net数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经写了这个查询得到一些结果,如果我想保存在一个数组我有什么做的结果?
我想用这是在col1和COL2在IF语句中的值,这就是为什么我想将它们保存在数组中。

  VAR CON =新的SqlConnection(数据源=本地;初始目录=测试;集成安全性=真);使用(CON)
使用(VAR命令=新的SqlCommand(SELECT COL1,COL2一些表,CON))
{
   con.Open();
   command.ExecuteNonQuery();
}


解决方案

通常情况下我使用的是类这样的:

 公共类类名
{
    公共字符串COL1 {搞定;组; }
    公众诠释col2的{搞定;组; }
}

现在你可以使用一个循环来填充列表和的ToArray 如果你真的需要一个数组:

 类名[] allRecords = NULL;
字符串SQL = @SELECT COL1,COL2
               从一些表;
使用(VAR命令=新的SqlCommand(SQL,CON))
{
    con.Open();
    使用(VAR读卡器= Command.ExecuteReader却())
    {
        VAR名单=新名单,LT;类名>();
        而(reader.Read())
            list.Add(新类名{COL1 = reader.GetString(0),col2的= reader.GetInt32(1)});
        allRecords = list.ToArray();
    }
}

请注意,我已经presumed第一列是字符串和第二的整数 。只是为了证明C#是类型安全,以及如何使用 DataReader.GetXY 方法。

I have wrote this query to get some results, if I want to save the results in an array what I have to do? I want to use the values which are in col1 and col2 in an IF statement, that's why I am thinking to save them in an array.

var con = new SqlConnection("Data Source=local;Initial Catalog=Test;Integrated Security=True");

using (con)
using (var command = new SqlCommand("SELECT col1,col2 FROM  some table", con))
{
   con.Open();
   command.ExecuteNonQuery();
}

解决方案

Normally i use a class for this:

public class ClassName
{
    public string Col1 { get; set; }
    public int Col2 { get; set; }
}

Now you can use a loop to fill a list and ToArray if you really need an array:

ClassName[] allRecords = null;
string sql = @"SELECT col1,col2
               FROM  some table";
using (var command = new SqlCommand(sql, con))
{
    con.Open();
    using (var reader = command.ExecuteReader())
    {
        var list = new List<ClassName>();
        while (reader.Read())
            list.Add(new ClassName { Col1 = reader.GetString(0), Col2 = reader.GetInt32(1) });
        allRecords = list.ToArray();
    }
}

Note that i've presumed that the first column is a string and the second an integer. Just to demonstrate that C# is typesafe and how you use the DataReader.GetXY methods.

这篇关于如何保存选择SQL查询结果在C#Asp.net数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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