This article lists the program source code and notes for connecting C # To Access, SQL Server, Oracle, MySQL, DB2, and SyBase.
1. C # connect to Access
Program code:
1 using System. Data;
2 using System. Data. OleDb;
3 ..
4 string strConnection = "Provider = Microsoft. Jet. OleDb.4.0 ;";
5 strConnection + = @ "DataSource = C: BegASPNETNorthwind. mdb ";
6 OleDbConnection objConnection = new OleDbConnection (strConnection );
7 ..
8objConnection. Open ();
9objConnection. Close ();
Explanation:
To connect to the Access database, you need to import additional namespaces. Therefore, the first two using commands are required!
The strConnection variable stores the connection string required to connect to the database. It specifies the data provider to be used and the data source to be used.
"Provider = Microsoft. jet. oleDb.4.0; "is the index data provider. Here, the Microsoft Jet Engine is used, that is, the Data Engine in Access. asp.net is connected to the Access database.
"Data Source = C: BegASPNETNorthwind. mdb" indicates the location of the Data Source. Its standard format is "Data Source = MyDrive: MyPathMyFile. MDB ".
PS:
1. the "@" symbol after "+ =" prevents the "" in the subsequent strings from being parsed as escape characters.
2. If the database file to be connected is in the same directory as the current file, you can use the following method to connect:
1 strConnection + = "Data Source = ";
2 strConnection + = MapPath ("Northwind. mdb ");
3. Note that parameters in the connection string must be separated by semicolons.
"OleDbConnection objConnection = new OleDbConnection (strConnection);" is a connection object created using a defined connection string. We will deal with this object in future operations on the database.
"ObjConnection. Open ();" is used to Open the connection. Now, the connection to the Access database is complete.
2. C # connect to SQL Server
Program code:
1 using System. Data;
2 using System. Data. SqlClient;
3 ..
4 string strConnection = "user id = sa; password = ;";
5 strConnection + = "initial catalog = Northwind; Server = YourSQLServer ;";
6 strConnection + = "Connect Timeout = 30 ";
7 SqlConnection objConnection = new SqlConnection (strConnection );
8 ..
9