我在一个桌面应用程序上,通过此函数检索本地服务器上的数据库列表
/// <summary>
/// This function populates the databases list in the drop down after the user is connected.
/// </summary>
public void BindDBDropDown()
{
//Create the connection object
SqlConnection sConnection = new SqlConnection("Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp");
//To Open the connection.
sConnection.Open();
//Query to select the list of databases.
string selectDatabaseNames = @"SELECT
NAME
FROM
MASTER..SYSDATABASES";
//Create the command object
SqlCommand sCommand = new SqlCommand(selectDatabaseNames, sConnection);
try
{
//Create the data set
DataSet sDataset = new DataSet("master..sysdatabases");
//Create the dataadapter object
SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectDatabaseNames, sConnection);
sDataAdapter.TableMappings.Add("Table", "master..sysdatabases");
//Fill the dataset
sDataAdapter.Fill(sDataset);
//Bind the database names in combobox
DataViewManager dsv = sDataset.DefaultViewManager;
//Provides the master mapping between the sourcr table and system.data.datatable
cmbDatabases.DataSource = sDataset.Tables["master..sysdatabases"];
cmbDatabases.DisplayMember = "NAME";
cmbDatabases.ValueMember = ("NAME");
}
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog logException = new EventLog("Application");
logException.Source = "MFDBAnalyser";
logException.WriteEntry(ex.Message);
}
finally
{
//If connection is not closed then close the connection
if(sConnection.State != ConnectionState.Closed)
{
sConnection.Close();
}
}
}如果我让它硬编码,这个函数可以很好地工作,但是当我尝试使用在app.config文件中声明的连接字符串时
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ConnectionString" value="Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp"/>
</appSettings>
</configuration>那它就不工作了..。
我需要做什么??
发布于 2010-11-30 21:31:45
您可以从System.Configuration命名空间和库中的AppSettingsReader类轻松访问应用程序设置。
AppSettingsReader asr = new AppSettingsReader();
SqlConnection sConnection = new SqlConnection(asr.GetValue("ConnectionString", typeof(string)).ToString());但对于连接字符串,微软提供了ConnectionStringSection
您可以在app.config文件中使用它,类似于应用程序设置部分:
<configuration>
<connectionStrings>
<add name="ConnectionString" connectionString="Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>并像这样访问它:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString)但是,正如MrEyes所说,您需要确保app.config文件位于主应用程序的项目中,否则它不会自动用作应用程序的默认配置。
发布于 2010-11-30 19:28:08
您在上面发布的代码是否使用了单独的类库作为您的主可执行文件?
添加应用程序设置的app.config是类库项目的一部分吗?
如果这两个问题都是肯定的,那么ConfigurationManager看起来就不是您期望的样子。框架将在app.config文件中查找您的可执行文件(编译后的yourexesname.exe.config)。因此,如果您将应用程序设置移动到那里,代码应该可以工作。
发布于 2010-11-30 19:31:20
你尝试这样做,如下所示
if (!String.IsNullOrEmpty(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString))
{
}如果是,那么应该没有任何问题。
https://stackoverflow.com/questions/4313159
复制相似问题