본문 바로가기
C#

ADO.net DB Connect

by 캡틴노랑이 2021. 3. 27.
반응형

 

 

ADO.net DB connect

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.SqlTypes;
 
namespace BIZ.Common.Dac
{
    public class ADOConnect
    {
        public DataSet GetDataSet(string database, string storeProcedure, Dictionary<string, object> dicParams )
        {
            string connectingString = "Data Source = 192.168.18.13; Initial Catalog = " + database + "; Persist Security Info=True;User ID = sa; Password=1111" ;
 
            var cmd = new SqlCommand();
            var ds = new DataSet();
 
 
            using (var con = new SqlConnection(connectingString))
            using (var adp = new SqlDataAdapter(cmd))
            {
                con.Open();
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = storeProcedure;
 
 
                SqlParameterCollection parameters = cmd.Parameters;
 
                foreach(KeyValuePair<string, object> pair in dicParams)   //Type value = ((object)333).GetType();
                {
                    switch(pair.Value.GetType().ToString())
                    {
                        case "System.Int32":
                            parameters.Add(new SqlParameter("@" + pair.Key.ToString(), (int)pair.Value));
                            break;
                        case "System.String":
                            parameters.Add(new SqlParameter("@" + pair.Key.ToString(), (string)pair.Value));
                            break;
                    }
                }
                 
                adp.Fill(ds);
                con.Close();
 
                return ds;
            }
        }
    }
}

 

 

사용법

1
2
3
Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("param1", "111");
DataSet data = (new ADOConnect()).GetDataSet("Kaishaku", "Z_UP_COCKTAIL_MATERIAL_LIST", dic);

 

 

 

 

 

반응형

댓글