如何使用C#将数据插入到MS访问文件? [英] How to insert data into MS access file using C#?

查看:105
本文介绍了如何使用C#将数据插入到MS访问文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个名为login的表的访问文件。这些列是用户名和密码。

I have created an access file with a table named "login". The columns are username and password.

现在我想用表格的用户名和密码添加新成员。信息将从textbox1和textbox2中获取。

Now i want to add new members to the table with their username and password. The information will be obtained from textbox1 and textbox2.

我该如何做?

顺便说一句,什么是连接字符串?是从数据库属性?
我得到的是@ Provider = Microsoft.ACE.OLEDB.12.0;数据源= C:\Users\qianren\Desktop\iplan版本\WindowsFormsApplication2\WindowsFormsApplication2\bin\Debug \log.accdb。这是对的吗?

By the way, what is the connection string? Is it from the database properties? what i get is "@Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\qianren\Desktop\iplan version\WindowsFormsApplication2\WindowsFormsApplication2\bin\Debug\log.accdb". Is it correct? Is it the right way to write the connectionstring?

推荐答案

首先需要添加一个对Microsoft.Office.Interop的引用。

First of all you need to add a reference to Microsoft.Office.Interop.Access under the .Net tab in the 'Add Reference' dialog box in Visual Studio.

然后创建两个变量,一个用于textbox1文本,另一个用于textbox2文本像这样:

Then create two variables, one for your textbox1 text, another for your textbox2 text like so:

var foo = textbox1.Text;
var bar = textbox2.Text;

然后使用Microsoft.Office.Interop.Access; $ c>到您的使用语句。

Then add using Microsoft.Office.Interop.Access; to your using statements.

然后您需要创建一个新的Application类实例,所以添加以下到您的方法:

Then you need to make a new instance of the Application class so add the following to your method:

var ap = new Microsoft.Office.Interop.Access.Application();

然后打开您的数据库:

ap.OpenCurrentDatabase(@"C:\Users\qianren\Desktop\iplan version\WindowsFormsApplication2\WindowsFormsApplication2\bin\Debug\log.accdb");

然后运行如下插入查询:

Then run an insert query like so:

ap.DoCmd.RunSQL(String.Format("INSERT INTO login ( Username, [Password] ) SELECT "{0}" AS LG, "{1}" AS PW;", foo, bar));

如果您不确定语法,可以使用Microsoft Access查询设计器设计此查询,单击在屏幕右下方的SQL按钮上复制SQL。

If you are unsure of the syntax, you can design this query using the Microsoft Access query designer, click on the SQL button on the bottom right hand side of the screen and copy the SQL over.

然后关闭数据库,如下所示:

Then close your database like so:

ap.CloseCurrentDatabase();

最后,按如下方式清理您的非托管对象:

Finally, clean up your unmanaged object like this:

Marshal.ReleaseComObject(ap); //Sorry this is nearly a year late, just noticed it!

这篇关于如何使用C#将数据插入到MS访问文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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