C# 操作Access数据文件

C# 操作Access数据文件

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OleDb;
using System.Data;

namespace IPSwitch
{
    /// <summary>
    /// 处理access的类
    /// </summary>
    public class DBReadAccess
    {
        /// <summary>
        /// Access 的数据库连接字符串.
        /// </summary>
        private const String connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database.mdb";
        private static OleDbConnection conn = null;

        /// <summary>
        /// 单例 返回连接对象
        /// </summary>
        /// <returns></returns>
        private static OleDbConnection GetConn()
        {
            if (conn == null)
            {
                conn = new OleDbConnection(connString);// 建立数据库连接.
            }
            return conn;
        }
        /// <summary>
        /// 初始化实例
        /// </summary>
        public DBReadAccess()
        {
            DBReadAccess.GetConn();
        }

        /// <summary>
        /// 根据sql语句,获取datatable
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataTable GetDataTableBySQL(string sql)
        {
            DataTable dt = new DataTable();
            OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn);// 创建一个适配器
            adapter.Fill(dt);//绑定table
            conn.Close();// 关闭数据库连接.
            return dt;
        }
        /// <summary>
        /// 根据sql语句查询第一行第一列的值
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public object GetObjectBySQL(string sql)
        {
            conn.Open();
            OleDbCommand cmd = conn.CreateCommand();// 创建一个 Command.
            cmd.CommandText = sql;// 定义需要执行的SQL语句.
            object obj = cmd.ExecuteScalar();//查询第一行第一列
            conn.Close();// 关闭数据库连接.
            return obj;
        }
        /// <summary>
        /// 根据sql语句执行更新语句
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public int GetInsertBySQL(string sql)
        {
            conn.Open();
            OleDbCommand cmd = conn.CreateCommand();// 创建一个 Command.
            cmd.CommandText = sql;// 定义需要执行的SQL语句.
            int num = cmd.ExecuteNonQuery();
            conn.Close();// 关闭数据库连接.
            return num;
        }
        /// <summary>
        /// 根据sql语句执行删除语句
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public int GetDeleteBySQL(string sql)
        {
            conn.Open();
            OleDbCommand cmd = conn.CreateCommand();// 创建一个 Command.
            cmd.CommandText = sql;// 定义需要执行的SQL语句.
            int num = cmd.ExecuteNonQuery();
            conn.Close();// 关闭数据库连接.
            return num;
        }
    }
}

 

你可能感兴趣的:(C# 操作Access数据文件)