When Asp.net connects to the Access database, we usually write the database connection string into the web.config configuration file. The database path in the connection string can only be expressed in the form of an absolute path. If you want to move the program, you must modify the database path of the database connection string in web.config, which is very troublesome. It is also incorrect if it is written in a relative path format such as ~/database/test.mdb. For example:
<connectionstrings> <add name="Access" connectionstring="Provider=Microsoft.Jet.OLEDB.4.0;data source=~/database/test.mdb" providername="System.Data.OleDb" /> </connectionstrings>
The above is written incorrectly.
There are currently 2 common solutions:
1. By using the DataDirectory keyword method
Starting from Asp.net 2.0, there is an App_Data directory to specifically store data files. It can be used to store Access, SQL Server Express, XML, etc. data file. You can place the Access database file in the App_Data folder, and then use the keyword DataDirectoty to get the path.
<connectionstrings> <add name="Access" connectionstring="Provider=Microsoft.Jet.OLEDB.4.0;data source=|DataDirectory|test.mdb" providername="System.Data.OleDb" /> </connectionstrings>
2. Set two strings in the web.config file
Set two strings in the web.config file, one is the driver string and the other is the relative path of the Access database file. When using it, use Server.MapPath() to obtain the absolute path, and then the combined connection string can be used.
<connectionStrings> <add name="Access" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;data source={0}" providerName="System.Data.OleDb" /> </connectionStrings> <appSettings> <add key="AccessPath" value="~/Database/test.mdb"/> </appSettings>
When used in the background, the code is as follows:
private string GetConnStr() { string connStr = WebConfigurationManager.ConnectionStrings["Access"].ConnectionString; connStr = connStr.Replace("{0}", Server.MapPath(WebConfigurationManager.AppSettings["AccessPath"].ToString())); return connStr; }