博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#中数据库的连接

Posted on 2008-06-13 14:23  庞滨  阅读(284)  评论(0编辑  收藏  举报

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;

namespace DAL
{
    public class DBAccess
    {
        private SqlConnection objConn;
        private SqlCommand objComm;

        public DBAccess(string strConn)
        {
            objConn = new SqlConnection(strConn);  
       
        }
        //增,删,改
        public bool ExecuteSQL(string strSQL,out string strMessage)
        {
            try
            {
                objConn.Open();
                objComm = new SqlCommand(strSQL, objConn);
                strMessage = objComm.ExecuteNonQuery().ToString();
                return true;
            }
            catch (Exception ex)
            {
                strMessage = ex.Message;
                return false;
            }
            finally
            {
                if(objConn!=null)
                {
                    objConn.Close();
                }
           }
        }

       
        //查
        public bool SearchSQL(string strSelSQL, out DataSet dsResult, out string strMessage)
        {
            DataSet objDataSet = new DataSet();
            try
            {
                objConn.Open();
                SqlDataAdapter objSqlDataAdapter = new SqlDataAdapter(strSelSQL,objConn);
                objSqlDataAdapter.Fill(objDataSet);
                strMessage = "";
                return true;
            }
            catch (Exception ex)
            {
                strMessage = ex.Message;
                return false;
            }
            finally
            {
                dsResult = objDataSet;
                if(objConn!=null)
                {
                    objConn.Close();
                }
            }
        }
    }
}