将DataSet的内容提取到对象中

时间:2017-07-03 12:31:12

标签: c# sql sql-server

我有DataSet调用我的Stored Procedure并返回一个整数列表。如何提取可以存储在变量中的整数列表,它是一个大小增长的集合,如List<T>或原始数据类型,如array整数。

以下是我的代码:

 private DataSet getSubGroupsBelongingToUser()
        {
            DataTable variable;
            DataSet DS;
            myConnectionString = ConfigurationManager.ConnectionStrings["FSK_ServiceMonitor_Users_Management.Properties.Settings.FSK_ServiceMonitorConnectionString"].ConnectionString;

            using (mySQLConnection = new SqlConnection(myConnectionString))
            {
                SqlParameter param = new SqlParameter("@UserId", getUserID(cbxSelectUser.Text));
                DS = GetData("Test", param);
                variable = DS.Tables[0];

            }


            return DS;
        }

当我将鼠标悬停在DS放大镜上时(参见图片): enter image description here

我想在某处检索并存储整数列表。我该怎么做呢?我在网上遇到的所有例子都使用了linq,这在这里不适用,因为我从我的存储过程中得到了需要一个输入参数的结果。以下是存储过程的定义:

create proc [dbo].[Test]
@UserId smallint
as
begin
    select DepartmentSubGroupId from DepartmentSubGroupUser
    where UserId= @UserId
end
GO

因此,当您传入UserId时,您应该获得这些值。我使用SQL Server作为我的DBMS。

3 个答案:

答案 0 :(得分:2)

最简单,最有效的方法是根本不使用conda install / Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\numpy\core\__init__.py", line 16, in <module> from . import multiarray ImportError: DLL load failed: The specified procedure could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\runpy.py", line 183, in _run_module_as_main mod_name, mod_spec, code = _get_module_details(mod_name, _Error) File "C:\ProgramData\Anaconda3\lib\runpy.py", line 142, in _get_module_details return _get_module_details(pkg_main_name, error) File "C:\ProgramData\Anaconda3\lib\runpy.py", line 109, in _get_module_details __import__(pkg_name) File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\__init__.py", line 5, in <module> from .deprecated import resolve_model_name File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\deprecated.py", line 8, in <module> from .cli import download File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\cli\__init__.py", line 5, in <module> from .train import train, train_config File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\cli\train.py", line 8, in <module> from ..scorer import Scorer File "C:\ProgramData\Anaconda3\lib\site-packages\spacy\scorer.py", line 4, in <module> from .gold import tags_to_entities File "spacy/morphology.pxd", line 25, in init spacy.gold (spacy/gold.cpp:23505) cdef class Morphology: File "spacy/vocab.pxd", line 27, in init spacy.morphology (spacy/morphology.cpp:10713) cdef class Vocab: File ".env/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd", line 155, in init spacy.vocab (spacy/vocab .cpp:19463) File "C:\ProgramData\Anaconda3\lib\site-packages\numpy\__init__.py", line 142, in <module> from . import add_newdocs File "C:\ProgramData\Anaconda3\lib\site-packages\numpy\add_newdocs.py", line 13, in <module> from numpy.lib import add_newdoc File "C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\__init__.py", line 8, in <module> from .type_check import * File "C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\type_check.py", line 11, in <module> import numpy.core.numeric as _nx File "C:\ProgramData\Anaconda3\lib\site-packages\numpy\core\__init__.py", line 26, in <module> raise ImportError(msg) ImportError: Importing the multiarray numpy extension module failed. Most likely you are trying to import a failed build of numpy. If you're working with a numpy git repo, try `git clean -xdf` (removes all files not under version control). Otherwise reinstall numpy.

DataSet

如果你坚持使用DataTable,至少它更为明确:

private List<int> GetSubGroupsBelongingToUser()
{
    List<int> list = new List<int>();
    using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["FSK_ServiceMonitor_Users_Management.Properties.Settings.FSK_ServiceMonitorConnectionString"].ConnectionString))
    using (var cmd = new SqlCommand("Test", con))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        var param = new SqlParameter("@UserId", SqlDbType.Int).Value = int.Parse(cbxSelectUser.Text);
        cmd.Parameters.Add(param);
        con.Open();
        using (var rd = cmd.ExecuteReader())
        {
            while (rd.Read()) list.Add(rd.GetInt32(0)); 
        }
    } // no need to close the connection with the using

    return list;
}

答案 1 :(得分:1)

正如@David所指出的,最简单的选择是使用SqlDataReader并遍历所有记录。

但是,如果您的心脏设置在DataTable s上,那么您需要做的就是迭代结果表中的所有行,从列DepartmentSubGroupId中获取值并将其添加到列表中。您可以使用Linq这样做:

return DS.Tables[0].Rows
    .Cast<DataRow>() // Rows is an ICollection and you need to cast each item
    .Select(r => (int)r["DepartmentSubGroupId"]) // For each row get the value from column DepartmentSubGroupId 
    .ToList();

答案 2 :(得分:0)

在我看到@Tim的解决方案之前,我已经准备好了(这与上述大多数解决方案一样有效):

...
    # Wait for queue to empty
    while not workQueue.empty():
        for (i, t) in enumerate(threads):
            if not t.is_alive():
                print("Recreating thread " + t.name)
                thread = myThread(threadID, threadList[i], workQueue,queueLock)
                thread.start()
                threads[i] = thread
                threadID += 1
...

谢谢大家,非常感谢。