日期:2014-05-19  浏览次数:20766 次

通过ConfigurationSettings.ConnectionStrings的问题
很多教材包含MSDN上都有介绍通过ConfigurationSettings.ConnectionStrings
获取App.config数据库连接信息的方法。
例如
ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VSADD.v10.en/dnvs05/html/vsgenerics.htm

中介绍

  A   typical   ADO.NET   2.0   connection   string   in   an   app.config   file   looks   like   this:
<configuration>
  <connectionStrings>
      <add   name= "Publications "   providerName= "System.Data.SqlClient "  
          connectionString= "Data   Source=MyServer;Initial   Catalog=pubs;
                                              integrated   security=SSPI "   />
  </connectionStrings>
</configuration>
获取连接信息的教本如下:
public   DbConnection   GetInitializedConnectionBaseClass()
{
DbConnection   conn   =   null;
ConnectionStringSettings   s   =        
    ConfigurationSettings.ConnectionStrings[ "Publications "];
DbProviderFactory   f   =   DbProviderFactories.GetFactory(
    s.ProviderName);

if   ((f.SupportedClasses   &   DbProviderSupportedClasses.DbConnection)   >   0)
  {
    conn   =     f.CreateConnection();
    conn.ConnectionString   =   s.ConnectionString;
  }
return   conn;
}


但是我的机器上无法执行,应为ConfigurationSettings根本没有ConnectionString属性,只有AppSettings属性可以选择,是我的设置有问题还是其他什么原因。
我用的是vs2005+.net   2.0
我引入的命名空间如下
using   System;
using   System.Collections.Generic;
using   System.ComponentModel;
using   System.Data;
using   System.Drawing;
using   System.Text;
using   System.Windows.Forms;
using   System.Data.Common;
using   System.Configuration;
using   System.Data.SqlClient;
我的app.config   文件如下
<?xml   version= "1.0 "   encoding= "utf-8 "   ?>
<configuration>
        <configSections>
        </configSections>
        <connectionStrings>
                <add   name= "WindowsApplication2.Properties.Settings.NorthwindConnectionString "
                        connectionString= "Data   Source=localhost;Initial   Catalog=Northwind;Integrated   Security=True "
                        providerName= "System.Data.SqlClient "   />
        </connectionStrings>
</configuration>



------解决方案--------------------
抱歉 多打了

应该是

System.Configuration.ConfigurationManager.ConnectionStrings[ "WindowsApplication2.Properties.Settings.NorthwindConnectionString "] 呵呵
------解决方案--------------------
LZ有心~
data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
这个好象是内置的一个数据库的连接
ASP.net里好象有用到,WINFORM里没怎么用过