通过Windows身份验证连接到SQL时出错

时间:2015-05-27 06:30:13

标签: c# connection-string

我使用以下代码连接到sql throgh windows身份验证。

string connctionstring = "connectionString={0};Database={1};Integrated Security=SSPI;";
string _connctionstring = string.Format(connctionstring, datasource, initialCatalogue);
SqlConnection _connection = new SqlConnection(_connctionstring);
_connection.Open();

但是我收到以下错误。请帮助。我可以通过sql server登录。

enter image description here

2 个答案:

答案 0 :(得分:5)

连接字符串format不正确 改为:

string connctionstring = "Data Source={0};Database={1};Integrated Security=SSPI;";

或者

string connctionstring = "Server={0};Database={1};Integrated Security=SSPI;";

答案 1 :(得分:2)

尽管Peyman's answer确实涵盖了基本问题(connectionString不是字符串的有效密钥),但更好的解决方案是使用SqlConnectionStringBuilder,这也有助于您正确转义如果你的字符串中有奇数字符(例如,如果你的数据库名称包含空格)

var scsb = new SqlConnectionStringBuilder();
scsb.DataSource = datasource;
scsb.InitialCatalog = initialCatalogue;
scsb.IntegratedSecurity = true;

//You also really should wrap your connections in using statements too.
using(SqlConnection connection = new SqlConnection(scsb.ConnectionString))
{
    connection.Open();
    //...
}