当前位置:数据库 > Access >>

c#小软件(SaveClassic)开发手记--(3)基础类(数据访问类DataAccess)

 

好些日子没整理自己的笔记了,实在是自己太忙了。我知道着不是借口,真是很累,根本就没有时间精力去整理这些笔记,现在稍微有点时间,我赶快整理一下思路。我想了想,今天还是把一些基本的类整理一下吧,这些都是我们在平常开发中经常见到的。这些内容,我自己感觉会有些毛病,希望大家帮忙改进一下,谢谢。

 

一、数据访问类DataAccess

数据访问类是我这个小软件最基础的类,它主要完成的功能就是,实现了对Access数据库的访问操作,具体代码如下。

 

using System.Data.OleDb;

 

using System.Data;

 

using System;

 

namespace Common

 

{

 

    public class DataAccess

 

    {

 

        protected static OleDbConnection conn = new OleDbConnection();

 

        protected static OleDbCommand comm = new OleDbCommand();

 

        public static string connstring = "";

 

        public DataAccess()

 

        {

 

        }

 

        private static void openConnection()

 

        {

 

            if (conn.State == ConnectionState.Closed)

 

            {

 

                conn.ConnectionString = @"Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + connstring;

 

                comm.Connection = conn;

 

            try

 

            {

 

            conn.Open();

 

            }

 

            catch (Exception e)

 

            { throw new Exception(e.Message); }

 

            }

 

        }

 

 

 

        private static void closeConnection()

 

        {

 

            if (conn.State == ConnectionState.Open)

 

            {

 

                conn.Close();

 

                conn.Dispose();

 

                comm.Dispose();

 

            }

 

        }

 

 

 

        public static void excuteSql(string sqlstr)

 

        {

 

            try

 

            {

 

                openConnection();

 

                comm.CommandType = CommandType.Text;

 

                comm.CommandText = sqlstr;

 

                comm.ExecuteNonQuery();

 

            }

 

            catch (Exception e)

 

            {

 

                throw new Exception(e.Message);

 

            }

 

            finally

 

            { closeConnection(); }

 

        }//执行sql语句

 

 

 

        public static OleDbDataReader dataReader(string sqlstr)

 

        {

 

            OleDbDataReader dr = null;

 

            try

 

            {

 

                openConnection();

 

                comm.CommandText = sqlstr;

 

                comm.CommandType = CommandType.Text;

 

 

 

                dr = comm.ExecuteReader(CommandBehavior.CloseConnection);

 

            }

 

            catch

 

            {

 

                try

 

                {

 

                    dr.Close();

 

                    closeConnection();

 

                }

 

                catch { }

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,