asp.net中数据库连接字符串的写法

2007数据库
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database1.accdb");

2003数据库
con=new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"数据库.mdb\";Jet OLEDB:Database Password=aking");
********************
private static void openConnection()
    {
        if (conn.State == ConnectionState.Closed )
        {
            conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
                + System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.ConnectionStrings["DbPath"].ToString());
            comm.Connection = conn;
            try
            {
                conn.Open();
               
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
    }

<connectionStrings>
  <add name="DBPath" connectionString="~/App_Data/Web.mdb"/>
  <!--数据库路径,前面的~必须保留-->
 </connectionStrings>

改为ACCESS后怎么写呢?

<connectionStrings>
  <add name="DBPath" connectionString="~/App_Data/Web.mdb"/>
  <!--数据库路径,前面的~必须保留-->
 </connectionStrings>

private static void openConnection()
    {
        if (conn.State == ConnectionState.Closed )
        {
            conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
                + System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.ConnectionStrings["DbPath"].ToString());
            comm.Connection = conn;
            try
            {
                conn.Open();
               
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
    }
这两个 加一块 就行了,前面 那个 在web.config中写

<appSettings>
    <add key="OLEDBCONNECTIONSTRING" value="provider=microsoft.jet.oledb.4.0;data source="/>
    <add key="dbPath" value="~/App_Data/Data.mdb"/>
  </appSettings>
***********************************************
public static OleDbConnection CreateDB()
 {
        return new OleDbConnection(ConfigurationManager.AppSettings["OLEDBCONNECTIONSTRING"].ToString() + System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["dbPath"]));
 }

你可能感兴趣的:(asp.net)