Based on MSDN data, there are two ways to connect to an Access database, namely:
First, connect to the Access database in Server Explorer
1. Create a connection in Server Explorer
Ii. connecting to an Access database from an application
1. Connect to an Access database visually
? To create a connection from Server Explorer
? To create a connection from the Data tab of the Toolbox
2. Connect to an Access database programmatically
? To programmatically create a connection between an application and an Access database
Programmatically manipulate an Access database in Visual Studio in C #, which is typically connected using OLE DB:
First, add a reference to 2 namespaces
Using System.Data;
Using System.Data.OleDb;
To define a new OLE DB connection
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection ();
Defines the connection string for OLE DB connections, which is the database to connect to
Conn. ConnectionString = @ "Provider=Microsoft.Jet.OLEDB.4.0;" +
@ "Data source= C:\Documents and settings\username\" +
@ "My Documents\accessfile.mdb";
Access2007, version 2010 to use
@ "Provider=microsoft.ace.oledb.12.0;data source=| DATADIRECTORY|\DATA\ZA_DATA.ACCDB ";
Open connection
Conn. Open ();
Close connection
Conn. Close ();
The general situation is:
1. Define OLE DB connections
OleDbConnection conn = new OleDbConnection ();
2. Define OLE DB connection string (database path)
Conn. ConnectionString = @ "Provider=microsoft.ace.oledb.12.0;data source=| DATADIRECTORY|\DATA\ZA_DATA.ACCDB ";
3. Define the connection command:
OleDbCommand command = new OleDbCommand ();
4. Define the properties of the OleDbCommand command:
⒈command.commandtext = "INSERT INTO";
Set the content to be executed according to the CommandType property setting
⒉command.commandtype = System.Data.CommandType.Text;
Set the type of the OleDbCommand command CommandText property
⒊command. Connection = conn;
Sets the connection for the OleDbCommand command, typically the OLE DB connection previously defined
5. Open the connection
Conn. Open ();
6, do other operations and processing, such as modify SQL string, define data reader (DataReader) and so on.
OleDbDataReader Reader = command. ExecuteReader ();
Reader.close ();
/* Here the contents of the Command.commandtext are read into the data reader reader and closed immediately after the reader data is processed, to be closed before the OLE DB connection is closed. */
7. Perform the required actions:
Command. ExecuteNonQuery ();
8. Close OLE DB connection:
Conn. Close ();
This method remains connected after the OLE DB connection has been opened, so be sure to close it after you have finished using it.
Visual Studio in C # connect directly to an Access database