How to insert data into MS access file using C #?

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

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

How can i do this?

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

+3


source to share


1 answer


First of all, you need to add a link to Microsoft.Office.Interop.Access on the .Net tab in the Add Link dialog box in Visual Studio.

Then create two variables, one for the text textbox1, the other for the text textbox2:

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

      

Then add using Microsoft.Office.Interop.Access;

to your statements.

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

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

      

Then open your database like this:

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

      



Then execute the insert query like this:

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

      

If you are not sure about the syntax, you can create this query using the Microsoft Access Query Designer, click the SQL button at the bottom right of the screen and copy the SQL.

Then close your database like this:

ap.CloseCurrentDatabase();

      

Finally, clean up your unmanaged object like this:

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

      

+3


source







All Articles