[已解决]从C#访问MS Access数据库 [英] [Solved]Accessing MS Access database from C#

查看:82
本文介绍了[已解决]从C#访问MS Access数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将MS Access用作C#Windows窗体应用程序的数据库.我已经使用OleDb驱动程序来连接MS Access.我可以使用OleDbConnection和ExecuteReader从MS Access中选择记录.但是我无法插入,更新和删除记录.我的代码如下:

I want to use MS Access as database for my C# windows form application.I have used OleDb driver for connecting MS Access. I am able to select the records from the MS Access using OleDbConnection and ExecuteReader.But I am unable to insert,update and delete records. My code is as follows:

OleDbConnection con=new OleDbConnection(strCon);
        try
        {
        con.Open();
        OleDbCommand com = new OleDbCommand("INSERT INTO DPMaster(DPID,DPName,ClientID,ClientName) VALUES(''53'',''we'',''41'',''aw'')", con);

        int a=com.ExecuteNonQuery();

        //OleDbCommand com = new OleDbCommand("SELECT * FROM DPMaster", con);
        //OleDbDataReader dr = com.ExecuteReader();
        //while (dr.Read())
        //{
        //    MessageBox.Show(dr[2].ToString());
        //}
        MessageBox.Show(a.ToString());
        }
        catch
        {
            MessageBox.Show("cannot");
        }



如果我执行注释的块,则应用程序可以工作.但是插入块不起作用.为什么我无法将记录插入/更新/删除到数据库中?
我的连接字符串如下:



If I execute the commented block the application works.But the insert block doesnt works.Why I am unable to insert/update/delete the records into database?
My Connection String is as follows:

string strCon="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=xyz.mdb;Persist Security Info=True";

推荐答案

OleDbCommand com = new OleDbCommand("INSERT INTO DPMaster(DPID,DPName,ClientID,ClientName)VALUES(" 53, " we","41","aw"),骗子);


我没有找到引起错误的任何内容,但是确切的错误声明可以进一步阐明问题,因此请在此处发布.

您使用插入查询的方式是一种非常不好的做法,请改用参数化查询.
OleDbCommand com = new OleDbCommand("INSERT INTO DPMaster(DPID,DPName,ClientID,ClientName) VALUES(''53'',''we'',''41'',''aw'')", con);


I am not finding anything that causing error, But the exactly error statement can clarify the thing further, So please post it here.

The way you''re using insert query is a very bad practice, Use Parameterized Query instead.


我已经找到了解决此问题的方法.

我将数据库保留在项目本身(解决方案)中,但是当我按照自己的建议将数据库保留在项目之外时,上面的代码可以正常工作.

我不知道这个问题与数据库文件的位置有什么关系.但是现在问题解决了.

如果有人知道为什么在解决方案内部有数据库的情况下代码为什么不起作用,请plz将其发布.

预先感谢.
I got solution for this problem.

I was keeping the database inside the project(solution) itself.But when I kept the database out of the project as per one''s suggestion, the above code works fine.

I don''t know what is the relation for this problem with the location of the database file.But now problem gets solved.

If any one has idea about why the code didn''t worked if we have the db inside the solution,plz post it.

Thanks in advance.


这篇关于[已解决]从C#访问MS Access数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆