程序开发 > C# > 正文

操作数据库常用类(C#)

秋月恒 2013-05-07 秋月怛

  操作数据库类中主要是一些连接数据库和执行sql语句的方法,源代码如下:


        // 打开数据库连接
        public void Open()
        {
            Page newpage = new Page();
            string db = ConfigurationSettings.AppSettings["Path"];
            ConnStr = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + newpage.Server.MapPath("~") + "\\" + db;
            if (conn == null)
                conn = new OleDbConnection(ConnStr);
         
            if (conn.State == ConnectionState.Closed)
            {
                try
                {
                    //打开数据库连接
                    conn.Open();
                }
                catch (Exception ex)
                {
                    HttpContext.Current.Response.Write(ex.Message);
                }
                finally
                {
                    //关闭已经打开的数据库连接    
                }
            }

        }
 
        // 关闭数据库连接
        public void Close()
        {
            //判断连接是否已经创建
            if (conn != null)
            {
                //判断连接的状态是否打开
                if (conn.State == ConnectionState.Open)
                    conn.Close();
            }
        }
 
        //释放资源
        public void Dispose()
        {
            // 确认连接是否已经关闭
            if (conn != null)
             {
                conn.Dispose();
                conn = null;
            }
        }

        // 返回DataReader对象
        public OleDbDataReader Re_dr(sql Exsql,string strsql)
        {
            OleDbCommand Comm = new OleDbCommand(strsql, Exsql.conn);
            OleDbDataReader Dr = Comm.ExecuteReader();
            return Dr;
        }
 
        // 返回DataSet对象
        public DataSet Db_ds(sql Exsql, string strsql, string table)
        {
            Exsql.Open();
            OleDbDataAdapter dapter = new OleDbDataAdapter(strsql, Exsql.conn);
            DataSet ds = new DataSet();
            try
            {
                //"table"是你在DataSet中建立的表的名称,可以使用其它名字
                dapter.Fill(ds, table);           
            }
            catch{}
            finally
            {
                Exsql.Close();
            }
            return ds;
        }
 
本文浓缩标签:数据库常用类C#