关键代码:

using System;
using System.Data;
using System.Data.OleDb;
namespace CSharpUtilHelpV2
{
    /// <summary>
    /// 基于.NET 2.0的ACCESS数据简单操作类
    /// </summary>
    public class AccessUtilsV2
    {
        string ConnectString = string.Empty;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="path">access路径</param>
        public AccessUtilsV2(string path)
        {
            ConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path;
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="path">access路径</param>
        /// <param name="password">access密码</param>
        public AccessUtilsV2(string path, string password)
        {
            ConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Jet OLEDB:Database Password= " + password;
        }
        /// <summary>
        /// ExecuteNonQuery
        /// </summary>
        /// <param name="sql">查询,修改,删除sql语句</param>
        /// <param name="parameters">OleDbParameter参数;eg: new OleDbParameter("@categoryName","Test2")</param>
        /// <returns>操作影响行数</returns>
        public int ExecuteNonQuery(string sql, OleDbParameter[] parameters)
        {
            int _affectedRows = -1;
            using (OleDbConnection sqlcon = new OleDbConnection(ConnectString))
            {

                sqlcon.Open();
                using (OleDbCommand sqlcmd = new OleDbCommand(sql, sqlcon))
                {
                    if (parameters != null)
                        sqlcmd.Parameters.AddRange(parameters);
                    _affectedRows = sqlcmd.ExecuteNonQuery();
                }
            }
            return _affectedRows;
        }
        /// <summary>
        /// ExecuteReader
        /// </summary>
        /// <param name="sql">读取sql语句</param>
        /// <param name="parameters">OleDbParameter参数;eg: new OleDbParameter("@categoryName","Test2")</param>
        /// <returns>IDataReader</returns>
        public IDataReader ExecuteReader(string sql, OleDbParameter[] parameters)
        {
            OleDbConnection _sqlcon = new OleDbConnection(ConnectString);
            using (OleDbCommand _sqlcmd = new OleDbCommand(sql, _sqlcon))
            {
                if (parameters != null)
                    _sqlcmd.Parameters.AddRange(parameters);
                _sqlcon.Open();
                return _sqlcmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
        }
        /// <summary>
        /// ExecuteDataTable
        /// </summary>
        /// <param name="sql">读取sql语句</param>
        /// <param name="parameters">OleDbParameter参数;eg: new OleDbParameter("@categoryName","Test2")</param>
        /// <returns>DataTable</returns>
        public DataTable ExecuteDataTable(string sql, OleDbParameter[] parameters)
        {
            using (OleDbConnection _sqlcon = new OleDbConnection(ConnectString))
            {
                using (OleDbCommand _sqlcmd = new OleDbCommand(sql, _sqlcon))
                {
                    if (parameters != null)
                        _sqlcmd.Parameters.AddRange(parameters);
                    using (OleDbDataAdapter _sqldap = new OleDbDataAdapter(_sqlcmd))
                    {
                        DataTable _dt = new DataTable();
                        _sqldap.Fill(_dt);
                        return _dt;
                    }
                }
            }
        }
        /// <summary>
        /// ExecuteScalar
        /// </summary>
        /// <param name="sql">查询第一行第一列数据值</param>
        /// <param name="parameters">OleDbParameter参数;eg: new OleDbParameter("@categoryName","Test2")</param>
        /// <returns>Object</returns>
        public Object ExecuteScalar(string sql, OleDbParameter[] parameters)
        {
            using (OleDbConnection _sqlcon = new OleDbConnection(ConnectString))
            {
                using (OleDbCommand _sqlcmd = new OleDbCommand(sql, _sqlcon))
                {
                    if (parameters != null)
                        _sqlcmd.Parameters.AddRange(parameters);
                    _sqlcon.Open();
                    return _sqlcmd.ExecuteScalar();
                }
            }
        }
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }测试代码:

using CSharpUtilHelpV2;
using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
namespace CSharpUtilHelpV2Test
{
    public class AccessUtilsV2Test
    {
        static AccessUtilsV2 AccessHelper = new AccessUtilsV2(string.Format(@"{0}\DB\Northwind.MDB", AppDomain.CurrentDomain.BaseDirectory.ToString()));
        public static void ShowAccessPath()
        {
            string _fullPath = string.Format(@"{0}\DB\Northwind.MDB", AppDomain.CurrentDomain.BaseDirectory.ToString());
            Console.WriteLine(_fullPath);
            Console.WriteLine("File.Exist:" + File.Exists(_fullPath));
        }
        public static void ExecuteNonQueryTest()
        {
            //-------------------------方式一---------------------------------------
            //string _sql = "INSERT INTO Categories (CategoryID, CategoryName, Description) VALUES   (22, 'Test', '测试')";
            //Console.WriteLine("ExecuteNonQueryTest:" + AccessHelper.ExecuteNonQuery(_sql, null));
            //-------------------------方式二---------------------------------------
            string _sql = "INSERT INTO Categories (CategoryID, CategoryName, Description) VALUES   (@id, @categoryName, @description)";
            OleDbParameter[] _paramter = new OleDbParameter[] {
               new OleDbParameter("@id",23),
               new OleDbParameter("@categoryName","Test2"),
               new OleDbParameter("@description","测试2")
            };
            Console.WriteLine("ExecuteNonQueryTest:" + AccessHelper.ExecuteNonQuery(_sql, _paramter));
        }
        public static void ExecuteReaderTest()
        {
            string _sql = "select * from Categories where CategoryID<=5";
            using (IDataReader reader = AccessHelper.ExecuteReader(_sql, null))
            {
                while (reader.Read())
                {
                    Console.WriteLine("CategoryID:" + reader["CategoryID"] + " CategoryName:" + reader["CategoryName"]);
                }
            }
        }
        public static void ExecuteDataTableTest()
        {
            string _sql = "select * from Categories where CategoryID<=5";
            Console.WriteLine("ExecuteDataTableTest:" + AccessHelper.ExecuteDataTable(_sql, null).Rows.Count);
        }
        public static void ExecuteScalarTest()
        {
            string _sql = "select * from Categories where CategoryID<=5";
            Console.WriteLine("ExecuteScalarTest:" + AccessHelper.ExecuteScalar(_sql, null) ?? "Null");
        }
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }测试结果:

这里是对Access操作的简单封装,希望有所帮助!

本人才疏学浅,难免错误,敬请指出,谢谢!

[C#]AccessUtils的更多相关文章

  1. .net(C#)在Access数据库中执行sql脚本

    自己写的一个工具类,主要是业务场景的需要. 主要有两个功能: ①执行包含sql语句的字符串 ②执行包含sql语句的文件 调用方式 /// <summary> /// 执行sql语句 /// ...

  2. HBase实践案例:知乎 AI 用户模型服务性能优化实践

    用户模型简介 知乎 AI 用户模型服务于知乎两亿多用户,主要为首页.推荐.广告.知识服务.想法.关注页等业务场景提供数据和服务, 例如首页个性化 Feed 的召回和排序.相关回答等用到的用户长期兴趣特 ...

随机推荐

  1. Windows下codeblocks的安装与配置

    最近自己正好要使用codeblocks编写C++程序,安装好却发现无法编译,如果您也遇到相似问题,可以参考本文. 如果您已安装codeblocks,想转换成中文界面,直接参考Step 2. 如果您C程 ...

  2. SQL Server中内连接和外连接的区别

    SQL Server中内连接和外连接的区别 假设一个数据库中有两张表,一张是学生表StudentInfo,一张是班级表ClassInfo,两张表之间用ClassId字段进行关联. 如果用内连接,正常的 ...

  3. launch failed.Binary not found in Linux/Ubuntu解决方案

    Linux下出现launch failed.Binary not found的解决方案: 首先当你把网上关于mingw的解决方案都看晕了的时候,告诉你,别看关于mingw的了.Linux下不用ming ...

  4. HTML 之 Embed兼容问题

    首先IE只支持对Object的解析,火狐.谷歌.Safari只支持对Embed的解析. 1.传统的方法 <object classid="clsid:d27cdb6e-ae6d-11c ...

  5. Sequence用堆排序

    Description Given m sequences, each contains n non-negative integer. Now we may select one number fr ...

  6. [改善Java代码]别让null值和空值威胁到变长方法

    建议5:别让null值和空值威胁到变长方法 public class Client { public void methodA(String str,Integer... is){ } public ...

  7. Oracle分页查询语句的写法(转)

    Oracle分页查询语句的写法(转)   分页查询是我们在使用数据库系统时经常要使用到的,下文对Oracle数据库系统中的分页查询语句作了详细的介绍,供您参考. Oracle分页查询语句使我们最常用的 ...

  8. ubuntu共享文件夹给virtualbox

    在ubuntu或者linuxmint等linux系统下安装了virtualbox,可以通过共享文件夹的方式,把文件夹共享给virtualbox下的虚拟机系统,我这里的虚拟机系统是win7,共享过程如下 ...

  9. Java Concurrency - ThreadFactory, 使用工厂方法创建线程

    当需要创建多个类似的线程实例时,使用工厂模式替代 new 操作符创建线程,能使代码更为简洁,易于维护.JDK 提供了 java.util.concurrent.ThreadFactory 接口,Thr ...

  10. Quartz Scheduler(2.2.1) - Usage of JobDataMap

    The JobDataMap can be used to hold any amount of (serializable) data objects which you wish to have ...