C#从SQL Server数据库获取结果,以便通过类

时间:2016-10-03 13:35:07

标签: c# sql-server

我对C#很新,所以请原谅我的无知。我有一个SQL Server表,我试图从该表中选择选择查询结果到C#中的表单组合框。

我试图做的是创建一个将在数据库端执行存储过程的类,我的绊脚石是如何将该类集成到代码中,以便结果显示在C#的下拉列表中。

这是我目前在C#中所拥有的内容。非常感谢您的帮助。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace MedicalOffice
{
    public class DBAIdSelect
    {
        public void SelectPractice()
        {
            using (SqlConnection cn = new SqlConnection())
            {
                cn.ConnectionString = GetConnectionString();
                cn.Open(); 

                using (SqlCommand cmd = new SqlCommand("SelectPracticeID"))
                {
                    cmd.Connection = cn;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.ExecuteNonQuery();
                }
            }
        }

        private string GetConnectionString()
        {
            string conString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
            return conString;
        }
    }
 }

SQL Server表:

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Practices]
(
    [PracticeID] [int] IDENTITY(1,1) NOT NULL,
    [PracticeName] [varchar](50) NULL,
    [Address1] [varchar](50) NULL,
    [Address2] [varchar](50) NULL,
    [City] [varchar](50) NULL,
    [State] [char](2) NULL,
    [Zip] [varchar](10) NULL,
    [IsActive] [bit] NULL,
    [DateCreated] [date] NULL 
        CONSTRAINT [DF_Practices_DateCreated]  DEFAULT (getdate()),
    [CreatedBy] [int] NULL,
    [DateModified] [date] NULL,
    [DateModifiedBy] [int] NULL,

    CONSTRAINT [PK_Practices] 
        PRIMARY KEY CLUSTERED ([PracticeID] ASC)
                WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
                      IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
                      ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

和存储过程:

create proc [dbo].[SelectPracticeID]
as
    select PracticeID
    from dbo.Practices
GO

2 个答案:

答案 0 :(得分:2)

只要您想调用存储过程,就可以使用此类,并返回DataTable

class myclass
{
     public DataTable SelectData(string proc, SqlParameter[] param)
     {
            DataTable Table = new DataTable();
            SqlCommand Cmd = new SqlCommand();
            Cmd.CommandType = CommandType.StoredProcedure;
            Cmd.CommandText = proc;
            Cmd.Connection = Acces.Connection;

            if (param != null)
                for (int i = 0; i < param.Length; i++)
                {
                    Cmd.Parameters.Add(param[i]);
                }

            SqlDataAdapter Adapter = new SqlDataAdapter(Cmd);
            Adapter.Fill(Table);

            return Table;
        }
     }

因此,只要您想使用任何返回结果集的存储过程,请使用它,如果您想执行任何数据:

public void ExecuteData(string proc, SqlParameter[] param)
{
    SqlCommand Cmd = new SqlCommand();
    Cmd.CommandType = CommandType.StoredProcedure;
    Cmd.CommandText = proc;
    Cmd.Connection = Acces.Connection;

    if (param != null)
    {
        Cmd.Parameters.AddRange(param);
    }

    Cmd.ExecuteNonQuery();
}

在你的类中创建这两个函数,并且每当你想调用类来返回一些数据或执行一些数据,如Insert,Update,Delete ......

你只需要打电话

function("Stored_Proc_Name", Parameters);

示例:

我想获得像你这样的选择程序:

  myclass classs = new myclass();
  DataTable Table = new DataTable();
  Table  = classs.SelectData("SelectPracticeID",null); //=cause there is no paramters in your stored proc 

因此Table将保存数据库发送的完整信息

答案 1 :(得分:0)

我建议为您的数据创建DTO&Simple / Poco。

这种&#34;方式&#34;需要更多的努力....但你的对象模型将是干净,漂亮和可维护的。

DataTables在2003年表现不错。2003年不再是这样了。以下是穷人的ORM&#34;,但很容易移植到Entity-Framework或NHibernate。数据集,数据集,尤其是无类型数据集,不易迁移。

[Serializable]
public partial class Practice
{
    public int PracticeKey { get; set; }                   
    public string PracticeName { get; set; }                   
}

[Serializable]
public class PracticeCollection : ICollection<Practice>
{
}   

internal static class PracticeDefaultLayout
{
    public static readonly int PRACTICE_KEY = 0;
    public static readonly int PRACTICENAME = 1;

}


public class PracticeSerializer
{   

    public PracticeCollection SerializeCollection(IDataReader dataReader)
    {
        Practice item = new Practice();
        PracticeCollection returnCollection = new PracticeCollection();
        try
        {

            int fc = dataReader.FieldCount;//just an FYI value

            int counter = 0;//just an fyi of the number of rows

            while (dataReader.Read())
            {

                if (!(dataReader.IsDBNull(PracticeSearchResultsLayouts.PRACTICE_KEY)))
                {
                    item = new Practice() { PracticeKey = dataReader.GetInt32(PracticeSearchResultsLayouts.PRACTICE_KEY) };

                    if (!(dataReader.IsDBNull(PracticeSearchResultsLayouts.PRACTICENAME)))
                    {
                        item.PracticeName = dataReader.GetString(PracticeSearchResultsLayouts.PRACTICENAME);
                    }


                    returnCollection.Add(item);
                }

                counter++;
            }

            return returnCollection;

        }
        //no catch here... see  http://blogs.msdn.com/brada/archive/2004/12/03/274718.aspx
        finally
        {
            if (!((dataReader == null)))
            {
                try
                {
                    dataReader.Close(); /* very important */ /* note, if your datareader had MULTIPLE resultsets, you would not close it here */
                }
                catch
                {
                }
            }
        }
    }
}








namespace MedicalOffice
{
    public class PracticeDataLayer
    {
        public ICollection<Practice> GetAllPractices()
        {
            using (SqlConnection cn = new SqlConnection())
            {
                cn.ConnectionString = GetConnectionString();
                cn.Open(); 

                using (SqlCommand cmd = new SqlCommand("SelectPracticeID"))
                {
                    cmd.Connection = cn;
                    cmd.CommandType = CommandType.StoredProcedure;
                    IDataReader idr = cmd.ExecuteReader();
                    return new PracticeSerializer().SerializeCollection(idr);
                    ////  idr.Close(); /* very important, currently the serializer closes it..so commented out here */  /* note, if your datareader had MULTIPLE resultsets, you would close the datareader AFTER you used all the resultsets */
                }
            }
        }

        private string GetConnectionString()
        {
            string conString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
            return conString;
        }
    }
 }