Please Enable JavaScript!
Gon[ Enable JavaScript ]

C# 데이타 베이스 처리를 위한 클래스 - Access DB

기타 언어/C# & MFC
반응형

C# 에서 데이터 베이스 처리를 위한 클래스를 따로 만들었다. MVC 모델로 분리하기위해

데이터베이스 관련기능만 따로 뽑아 정형화 시킨것이다. 원하는 데이터를 얻기위한 쿼리만

함수에 넘겨 실행한후 그 결과값을 받으면 된다.

주요내용은 연결문자열을 통한 연결객체만들기, 연결끊기, select 쿼리 수행, update,delete 쿼리

수행해서 리턴하는 함수들로 되어있다. 연결객체를 만드는 부분은 연결문자열내용만 바꾸면

다른 DB에 연결이 가능하여 여기에선 Access DB 연결을 위한 문자열이 셋팅되어있다.

 

select 쿼리를 수행하는 함수에서는 연결객체를 통해 쿼리를 수행하고 리턴받은 DataSet 에서

테이블에 해당하는 DataRowCollection 객체를 꺼내 리턴해준다.

OleDbDataAdapter 객체로 DataSet GON 이라는 이름으로 데이터를 채운후

gonDataSet.Tables["GON"].Rows; 통해 DataRowCollection 레퍼런스를 리턴받는다.

// 연결실행
connection = OpenSqlConnection();
OleDbCommand command = new OleDbCommand(sql, connection);
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
adapter.Fill(gonDataSet, "GON");

DataRowCollection rows = gonDataSet.Tables["GON"].Rows;
이렇게 리턴받은 DataRowCollection 을 이용하여 화면이나 기타 필요한 곳에 활용하면된다
DataRowCollection dataPopular = service.GetCurePopularList(no);
if (dataPopular != null)
{
   // 초기화 
  this.lstDisease.Items.Clear();
  this.lstDisease.BeginUpdate();
  foreach (DataRow dr in dataPopular) 
  {
     string[] arData = new string[3];
     arData[0] = dr["ID"].ToString();
     arData[1] = dr["질병"].ToString();
     arData[2] = dr["식물명"].ToString();
     ListViewItem lvt = new ListViewItem(arData, 0);
     this.lstDisease.Items.Add(lvt);
  }
  this.lstDisease.EndUpdate();
}
아래 소스는 데이터베이스 제어를 위한 클래스의 전체내용이다
class Access
{
    OleDbConnection conn = null;
    private static OleDbConnection OpenSqlConnection() 
    {
        OleDbConnection connection = null;
        try
        {
            if (connection == null || connection.State == ConnectionState.Closed)
            {
                string connStr = @"Provider=Microsoft.JET.OLEDB.4.0;"
                               + @"data source=약용식물.mdb;"
                               + @"Password=;";
                // 데이타베이스를연결객체를생성합니다.
                connection = new OleDbConnection(connStr);
                connection.Open(); // 커넥션개체를엽니다.
                Console.WriteLine("ServerVersion:{0}", connection.ServerVersion);
                Console.WriteLine("State:{0}", connection.State);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("[Connection Error]" + e.Message);
            throw;
        }
        return connection;
    }
    /// 
    /// select 쿼리를수행한다.
    /// 
    /// 
    /// 
    public DataRowCollection GetData(string sql)
    {
        OleDbConnection connection = null;
        DataSet gonDataSet = new DataSet();// 담을그릇

        // 데이타를가져와서DataSet 에담는다.
        try
        {
            // 연결실행
            connection = OpenSqlConnection();
            OleDbCommand command = new OleDbCommand(sql, connection);
            OleDbDataAdapter adapter = new OleDbDataAdapter(command);
            adapter.Fill(gonDataSet, "GON");
            DataRowCollection rows = gonDataSet.Tables["GON"].Rows;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error : Failed to retrieve the required data from the Database {0}",
                             ex.Message); ;
            return null;
        }
        finally
        {
            this.DisConncect(connection);
        }

        DataTableCollection data = gonDataSet.Tables;
        foreach (DataTable dt in data)
        {
            Console.WriteLine("Found data table {0}", dt.TableName);
        }
        // the next two lines hsow two difference ways you can get the 
        // count of tables in a dataset;
        Console.WriteLine("{0} tables in data set", gonDataSet.Tables.Count);
        Console.WriteLine("{0} tables in data set", data.Count);
        Console.WriteLine("{0} rows in Categories table", gonDataSet.Tables["GON"].Rows.Count);

        // the next serval lines show how to get information on
        // a specific table by name from the dataset:
        Console.WriteLine("{0} columns in Categories table", 
                         gonDataSet.Tables["GON"].Columns.Count);
        DataColumnCollection drc = gonDataSet.Tables["GON"].Columns;
        foreach (DataColumn dc in drc)
        {
            // Print the column subscript, then the column's name
            // and its data type;
            Console.WriteLine("Column name[{0}] is {1}", dc.ColumnName, dc.DataType);
        }
        return rows;
    }
    /// 
    /// update, delete 쿼리를실행한다.
    /// 
    /// 
    /// 
    public bool update(string sql)
    {
        bool result = true;
        OleDbConnection connection = null;
        try
        {
            // 연결실행
            connection = OpenSqlConnection();

            // 내용검색을위해서쿼리실행
            OleDbCommand cmd = new OleDbCommand(sql, connection);
            int queryResult = cmd.ExecuteNonQuery();
            if (queryResult == 0) result = false;
        }
        catch (Exception ex)
        {
            result = false;
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.StackTrace);
        }
        finally
        {
            this.DisConncect(connection);
        }
        return result;
    }
    /// 
    /// 엑세스DB 와연결을끊는다.
    /// 
    /// 
    public void DisConncect(OleDbConnection connection)
    {
        if (connection.State == ConnectionState.Open)
        {
            connection.Close();
        }
    }
}
반응형
Posted by 녹두장군1
,