关键代码:

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. 优秀js插件收藏

    1. 滚动视差效果,类似锤子主页等效果实现 https://github.com/hahnzhu/parallax.js 2. jQuery全屏滚动插件 http://www.dowebok.com/ ...

  2. HDFS原理讲解

    简介 本文是笔者在学习HDFS的时候的学习笔记整理, 将HDFS的核心功能的原理都整理在这里了. [广告] 如果你喜欢本博客,请点此查看本博客所有文章:http://www.cnblogs.com/x ...

  3. truncate 与 delete 的区别

    Delete删除的数据可以通过日志文件进行恢复 Truncate Table删除的数据不能进行恢复 Delete删除时,标识列取值保留原使用中最大值 Truncate Table删除时,标识列恢复到最 ...

  4. 在Linux使用mingw32来编写win32程序

    MinGW - Minimalist GNU For Windows Mingw32 是 GNU 計畫工具的集合,包含了大量的標頭檔(header files).函式庫與指 令程式.目的在提供免費的工 ...

  5. 解决Kscope中文乱码问题

    当安装Kscope完成后,然后配置以下三个路径:Cscope path:/usr/bin/cscopeCtags path:/usr/bin/ctagsDot path:/usr/bin/dot 对于 ...

  6. c语言趣味

    改编java趣味100题,c语言版 1.C语言版金字塔 #include <stdio.h> int main() { int n,i,j,k; scanf("%d", ...

  7. android 几个小技巧

    1.如果打开模拟器,不同程序打开了不同的模拟器.可能是某个某个模拟器的target版本过低,修改一下4.2,应该都可以用了 2.找不到R.id.的错误,不妨删除menu文件夹下的xml文件 3.act ...

  8. cocos2d-x 3.0 alpha1 生成Qt qch帮助文档

    Qt的助手挺好用的. 比chm好多了 cocos2d-x使用doxygen生成文档. 默认生成的是html形式, 需要打开浏览器, 这个是比较耗资源吧 可以修改配置, 让doxygen同时输出qch形 ...

  9. python读取文本、配对、插入数据脚本

    #在工作中遇见了一个处理数据的问题,纠结了很久,写下记录一下.#-*- coding:UTF-8 -*- #-*- author:ytxu -*- import codecs, os, sys, pl ...

  10. Simple Membership 学习笔记

    第一步:新建项目后添加对WebMartix.Data 和 WebMatrix.WebData的引用第二步:在web.config中添加membership配置节第三步:修改Global.asax文件 ...