如何在app.config文件中指定连接字符串 [英] how to specify connection string in app.config file
本文介绍了如何在app.config文件中指定连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
private void button1_Click(object sender, EventArgs e)
{
string str = ConfigurationSettings.AppSettings["ConnectionString"];
using (SqlConnection connection = new SqlConnection(str))
{ try
{
connection.Open(); ---throwing error here saying instance failure
}
catch (System.Data.SqlClient.SqlException ex)
{
return;
}
string selectCommandText = "SELECT * FROM tmptblUserProfile";
using (SqlDataAdapter adapter = new SqlDataAdapter(selectCommandText, connection))
{
using (DataTable table = new DataTable("tmptblUserProfile"))
{ adapter.Fill(table);
StringBuilder commaDelimitedText = new StringBuilder();
commaDelimitedText.AppendLine("col1|col2|col3|col4|col5|col6col7|col8|col9|col10|col11|col12|col13|col14|col15");
foreach (DataRow row in table.Rows) {
string value = string.Format("{0}|{1}|{2}|{3}|{4}|{5}{6}|{7}|{8}{9}|{10}|{11}{12}|{13}|{14}", row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], row[14]);
commaDelimitedText.AppendLine(value);
}
File.WriteAllText(@"C:\Documents and Settings\aj99823\Desktop\amal101.txt", commaDelimitedText.ToString());
}
}
}
}
在app.config中,我指定为
in the app.config i specified as
<configuration>
<appsettings>
<add key="ConnectionString">
value="Data Source=CSZ-PCS43132\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True"
/>
</add></appsettings>
</configuration>
执行此语句时,它抛出一个错误,说明实例失败.任何人都可以帮助我.............
it is throwing one error saying instance failure while executing this statement.can anyone plss help me.............
推荐答案
问题与您的配置文件无关,问题出在您的SQL Server实例名称上.检查CSZ-PCS43132 \\ SQLEXPRESS是否为有效的SQL Server实例. (此处CSZ-PCS43132是您的PC/服务器名称,而SQLEXPRESS是您的实例名称)
The problem is not with your config file, the problem is with your SQL Server instance name. Check if CSZ-PCS43132\\SQLEXPRESS is a valid SQL Server instance. (Here CSZ-PCS43132 is your PC/Server name and SQLEXPRESS is your instance name)
连接字符串的指定方式与在appconfig.ex
中的操作方式相同
connection string is specified just like how you did in appconfig.ex
<connectionStrings>
<clear />
<add name="Local" connectionString="Data Source=MyPC;Database=Northwind;user=sa;password=pass;" />
</connectionStrings>
似乎您的连接字符串不正确.您可以尝试使用相同的凭据打开SSMS.
It seems like your connection string is not correct.You can try to open SSMS using same credential.
您的问题是因为在"\\"中您的连接字符串应为
CSZ-PCS43132 \ SQLEXPRESS;初始目录=测试;集成安全性=真
如果有帮助,请将其标记为已回答
Your problem is because of in "\\" your connection string should be
CSZ-PCS43132\SQLEXPRESS;Initial Catalog=test;Integrated Security=True
Mark it as answered if it helps
这篇关于如何在app.config文件中指定连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文