错误消息:初始化字符串的格式不符合从索引0开始的规范

我搜索了SO,但没有找到我的错误的解决方案。
我正在使用VS 2013和SQL Server 2014。

以下是我的连接字符串:

using (SqlConnection sqlConnection = new SqlConnection("cnInvestTracker")) { } 

我的web.config是:

    

当代码执行using行时,我收到一条错误消息。 错误消息是:

初始化字符串的格式不符合从索引0开始的规范。

导致错误的原因是什么?

"cnInvestTracker" 本身不是有效的连接字符串。 你在这里尝试使用的是:

 new SqlConnection("cnInvestTracker") 

该构造函数不需要连接字符串的名称 ,它需要连接字符串本身 :

 new SqlConnection(ConfigurationManager.ConnectionStrings["cnInvestTracker"].ConnectionString) 

(您可能必须添加对System.Configuration的引用,并且您可能希望添加一些错误检查以确保在尝试引用该名称之前存在该名称的连接字符串。)

 using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["cnInvestTracker"].ConnectionString)) { } 

一旦建立连接,您可能希望对代码执行更多操作,因此下面是您希望使用.Fill()将数据返回到DataTable时可以执行的操作的示例

 SqlDataAdapter sda; DataTable someDataTable = new DataTable(); using (SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["cnInvestTracker"].ConnectionString)) { using (SqlCommand cmd = new SqlCommand("ups_GeMyStoredProc", connStr)) //replace with your stored procedure. or Sql Command { cmd.CommandType = CommandType.StoredProcedure; sda = new SqlDataAdapter(cmd); new SqlDataAdapter(cmd).Fill(someDataTable); } }