首页 > 数据库 >C#连接Access数据库 查询和新增 示例

C#连接Access数据库 查询和新增 示例

时间:2024-05-21 13:08:26浏览次数:23  
标签:return ole 示例 C# Access connection dt null string

C#连接Access数据库 查询和新增 示例

项目中需要做一个写程序操作日志的需求,仅本机使用。这时Access数据库就是一个非常好的选择,简单,好用。

下面仅仅是一个示例,简单写出 查询 和 新增 等 C#操作 Access 数据库的 代码

效果图

 clsDBHelperAccess.cs

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

namespace myClass
{
    class clsDBHelperAccess
    {
        private string conn_str = null;
        private OleDbConnection ole_connection = null;
        private OleDbCommand ole_command = null;
        private OleDbDataReader ole_reader = null;
        private DataTable dt = null;

        /// <summary>  
        /// 构造函数  
        /// </summary>  
        public clsDBHelperAccess()
        {
            conn_str = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\我的文档\Visual Studio 2008\Projects\AccessOperator\AccessOperator\bin\Debug\myDb.mdb'";
            InitDB();
        }
        /// <summary>  
        /// 构造函数  
        /// </summary>  
        /// <param name="db_path">数据库路径</param> 
        public clsDBHelperAccess(string db_path)
        {
            conn_str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + db_path + "'";
            InitDB();
        }

        private void InitDB()
        {
            ole_connection = new OleDbConnection(conn_str); //创建实例  
            ole_command = new OleDbCommand();
        }

        /// <summary>  
        /// 转换数据格式  
        /// </summary>  
        /// <param name="reader">数据源</param>  
        /// <returns>数据列表</returns>  
        private DataTable ConvertOleDbReaderToDataTable(ref OleDbDataReader reader)
        {
            DataTable dt_tmp = null;
            DataRow dr = null;
            int data_column_count = 0;
            int i = 0;
            data_column_count = reader.FieldCount;
            dt_tmp = BuildAndInitDataTable(data_column_count);
            if (dt_tmp == null)
            {
                return null;
            }
            while (reader.Read())
            {
                dr = dt_tmp.NewRow();
                for (i = 0; i < data_column_count; ++i)
                {
                    dr[i] = reader[i];
                }
                dt_tmp.Rows.Add(dr);
            }
            return dt_tmp;
        }

        /// <summary>  
        /// 创建并初始化数据列表  
        /// </summary>  
        /// <param name="Field_Count">列的个数</param>  
        /// <returns>数据列表</returns>  
        private DataTable BuildAndInitDataTable(int Field_Count)
        {
            DataTable dt_tmp = null;
            DataColumn dc = null;
            int i = 0;
            if (Field_Count <= 0)
            {
                return null;
            }
            dt_tmp = new DataTable();
            for (i = 0; i < Field_Count; ++i)
            {
                dc = new DataColumn(i.ToString());
                dt_tmp.Columns.Add(dc);
            }
            return dt_tmp;
        }
/// <summary> /// 从数据库里面获取数据 /// </summary> /// <param name="strSql">查询语句</param> /// <returns>数据列表</returns> public DataTable GetDataTableFromDB(string strSql) { if (conn_str == null) { return null; } try { ole_connection.Open(); //打开连接 if (ole_connection.State == ConnectionState.Closed) { return null; } ole_command.CommandText = strSql; ole_command.Connection = ole_connection; ole_reader = ole_command.ExecuteReader(CommandBehavior.Default); dt = ConvertOleDbReaderToDataTable(ref ole_reader); ole_reader.Close(); ole_reader.Dispose(); } catch (System.Exception e) { //Console.WriteLine(e.ToString()); ///clsLogHelper.m_CreateErrorLogTxt("clsDBHelperAccess ", "GetDataTableFromDB", e.Message.ToString()); } finally { if (ole_connection.State != ConnectionState.Closed) { ole_connection.Close(); } } return dt; } /// <summary> /// 执行sql语句 /// </summary> /// <param name="strSql">sql语句</param> /// <returns>返回结果</returns> public int ExcuteSql(string strSql) { int nResult = 0; try { ole_connection.Open(); //打开数据库连接 if (ole_connection.State == ConnectionState.Closed) { return nResult; } ole_command.Connection = ole_connection; ole_command.CommandText = strSql; nResult = ole_command.ExecuteNonQuery(); } catch (System.Exception e) { //Console.WriteLine(e.ToString()); //clsLogHelper.m_CreateErrorLogTxt("clsDBHelperAccess ", "ExcuteSql", e.Message.ToString()); return nResult; } finally { if (ole_connection.State != ConnectionState.Closed) { ole_connection.Close(); } } return nResult; } } }

Form1.cs  窗体中的部分主要代码

     private void butSelect_Click(object sender, EventArgs e)
        {
            DataTable dt =  Select("2024-01-01 00:00:00", "2024-12-30 00:00:00");
            if (dt == null)
                MessageBox.Show("查询信息发生异常!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            else if (dt.Rows.Count <= 0)
            {
                this.dataGridView1.DataSource = dt;
                MessageBox.Show("没有符合条件的信息!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                this.dataGridView1.DataSource = dt;
                this.lblRowCount.Text = dt.Rows.Count.ToString();
            }
        }

        //按 时间
        public DataTable Select(string strStartTime,string strStopTime)
        {
            try
            {
                string strSql = "";
                string strCol = "*";
                string strWhere = " ( date_time>='" + strStartTime + "' and date_time<='" + strStopTime + "') ";

                strSql = "select " + strCol + " from operation_log where  " + strWhere;
                //return DbHelperSQL.Query(strSql).Tables[0];
                string path = System.Windows.Forms.Application.StartupPath + @"\data\lansever_db.mdb";

                myClass.clsDBHelperAccess Helper = new myClass.clsDBHelperAccess(path);
                return Helper.GetDataTableFromDB(strSql);
            }
            catch (System.Exception e)
            {
                return null;
            }
        }

        private void butAdd_Click(object sender, EventArgs e)
        {
            int intResult = Add();
            if (intResult >= 1)
            {
                MessageBox.Show("添加成功!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("添加失败!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }

        //添加一条数据
        public int Add()
        {
            try
            {
                string strId = System.Guid.NewGuid().ToString();

                string strSize = "AAAAAA";
                string strDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string strButton = "BBBBB1";
                string strType = "CCCCCC2";
                string strRemarks = "";

                string strSql = "";
                strSql += "insert into operation_log (id,site,date_time,button,type,remarks ";
                strSql += " ) values( ";
                strSql += " '" + strId + "','" + strSize + "','" + strDateTime + "','" + strButton + "','" + strType + "','" + strRemarks + "' ";
                strSql += "  )";

                string path = System.Windows.Forms.Application.StartupPath + @"\data\lansever_db.mdb";

                myClass.clsDBHelperAccess Helper = new myClass.clsDBHelperAccess(path);
                return Helper.ExcuteSql(strSql);
            }
            catch (System.Exception e)
            {
                return 0;
            }

        }

 

标签:return,ole,示例,C#,Access,connection,dt,null,string
From: https://www.cnblogs.com/hailexuexi/p/18203751

相关文章

  • Leedcode-相对名次
    自己写的:fromtypingimportListclassSolution:deffindRelativeRanks(self,score:List[int])->List[str]:#获取成绩列表的长度n=len(score)#复制原始成绩列表score_former=score#对成绩列......
  • C#在DataGridView表格中操作Access数据库
    C#在DataGridView表格中直接添加修改删除数据 效果图 Form1.cs完整代码usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Dat......
  • ciscn2024初赛部分题目复现
    gdb_debug64位ida反编译,将主要加密部分使用chatgpt写成更容易理解的python形式如下:defencrypt_string(s):v17=[]foriinrange(len(s)):v17.append(ord(s[i])^rand_1[i])ptr=list(range(len(s)))forkinrange(len(s)-1,0,-1):......
  • FormCreate中在事件中获取api
    form-create中在事件中获取apiFormCreate是一个可以通过JSON生成具有动态渲染、数据收集、验证和提交功能的表单生成组件。支持5个UI框架,并且支持生成任何Vue组件。内置20种常用表单组件和自定义组件,再复杂的表单都可以轻松搞定FormCreate官网:https://www.form-create.com......
  • C#如何用最简单方法调用Python?
    最近有群友咨询C#如何调用Python?小编尝试Python.NET过程中遭遇的版本兼容性和环境配置难题,小编决定寻找一个更为简单、稳定且对初学者友好的解决方案。小编搜索一番,除了Python.NET之外,还有其他途径能够帮助我们轻松地在C#项目调用Python脚本,那就是通过命令行调用,使用System.Diagn......
  • form-create-designer中怎么扩展自定义组件
    form-create-designer中怎么扩展自定义组件form-create-designer是基于 @form-create/element-ui实现的表单设计器组件。可以通过拖拽的方式快速创建表单,提高开发者对表单的开发效率,节省开发者的时间。FormCreate官网:https://www.form-create.com帮助文档:https://pro.form-cr......
  • [CISCN 2022 初赛]online_crt crash漏洞引起的命令执行
    几天没做题了,有点生疏。看题吧。题目标签说是CVE-2022-1292,去看看。意思就是在$fname处构造恶意文件名导致的命令注入,而且前面没有认真过滤,也就是文件名命令执行。看看题目源码:点击查看代码importdatetimeimportjsonimportosimportsocketimportuuidfromcryptogr......
  • 【Halcon】实现分离通道、创建矩形、获取灰度级、求最大最小均值、求大于某一灰度级的
    read_image(Image,'D:/image/123.jpg')rgb1_to_gray(Image,GrayImage)gen_rectangle1(Rectangle,100,100,200,200)rectangle1_domain(GrayImage,ImageReduced,100,100,200,200)crop_domain(ImageReduced,ImagePart)get_region_points(ImageP......
  • Chardet: 通用字符编码检测器
    Chardet:通用字符编码检测器构建状态图片PyPI上的最新版本许可证检测ASCII、UTF-8、UTF-16(2个变体)、UTF-32(4个变体)Big5、GB2312、EUC-TW、HZ-GB-2312、ISO-2022-CN(繁体和简体中文)EUC-JP、SHIFT_JIS、CP932、ISO-2022-JP(日语)EUC-KR、ISO-2022-KR、Johab(韩语)KOI8-R、MacCy......
  • 易基因:WGBS+ChIP-seq等表观组分析揭示FOXM1 是抗肿瘤免疫应答的关键调控因子
    大家好,这里是专注表观组学十余年,领跑多组学科研服务的易基因。食管癌是一种常见的恶性肿瘤,包括两种主要的组织学亚型:食管鳞状细胞癌(squamouscellcarcinoma,ESCC)和食管腺癌(adenocarcinoma,EAC)。近两年来对抗肿瘤免疫应答机制的理解得到了显著提高,免疫检查点阻断(ICB)疗法等免疫疗......