C # ACCESS database processing
C # connect to the ACCESS Database
Program code:
--------------------------------------------------------------------------------
Code
Using System. Data;
Using System. Data. OleDb;
OleDbConnection connection = new OleDbConnection ("Provider = Microsoft. Jet. OLEDB.4.0;" +
"Data Source = C :\\ DbView \ tysql. mdb ");
// Open the database connection
Connection. Open ();
MessageBox. Show ("successful database connection ");
// Close the database connection
Connection. Close ();
MessageBox. Show ("the database connection is closed successfully ");
To connect to the Access database, you need to import additional namespaces. Therefore, the first two using commands are required!
"Provider = Microsoft. jet. oleDb.4.0; "is the index data provider. Here we use the Microsoft Jet Engine, which is the Data Engine in Access. asp.net is connected to the Access database.
"Data Source = C: \ BegASPNET \ Northwind. mdb" indicates the location of the Data Source. Its standard format is "Data Source = MyDrive: MyPath \ MyFile. MDB ".
Ps:
1. If the database file to be connected is in the same directory as the current file, you can use the following method to connect:
StrConnection + = "Data Source = ";
StrConnection + = MapPath ("Northwind. mdb ");
In this way, you can write a lot of things!
3. Note that parameters in the connection string must be separated by semicolons.
"OleDbConnection objConnection = new OleDbConnection (strConnection);" this sentence uses the defined connection string to create a link object. In the future, we will deal with this object for database operations.
"ObjConnection. Open ();" this is used to Open the connection. Now, the connection to the Access database is complete. Other operations (insert, delete...) can be found in related books.
C # query the ACCESS database
1 int num = 0; // Number of Members
2 string message = ""; // the pop-up result message.
3 // SQL statement used for query
4 string SQL = "SELECT COUNT (*) FROM Orders ";
5
6 try
7 {
8 connection. Open (); // Open the database connection
9 OleDbCommand command = new OleDbCommand (SQL, connection );
10 // Execute SQL query
11 num = (int) command. ExecuteScalar ();
12 message = string. Format ("the Orders table contains {0} student information! ", Num );
13 MessageBox. Show (message, "query result", MessageBoxButtons. OK, MessageBoxIcon. Information );
14
15}
16 catch (Exception exp)
17 {
18 // operation Error
19 MessageBox. Show (exp. Message );
20}
21 finally
22 {
23 // close the database connection
24 connection. Close ();
25}