C# 错误消息:初始化字符串的格式不符合从索引0开始的规范
我进行了搜索,但没有找到解决错误的方法。C# 错误消息:初始化字符串的格式不符合从索引0开始的规范,c#,asp.net,sql-server-2014,C#,Asp.net,Sql Server 2014,我进行了搜索,但没有找到解决错误的方法。 我使用的是VS 2013和SQL Server 2014 以下是我的连接字符串: using (SqlConnection sqlConnection = new SqlConnection("cnInvestTracker")) { } 我的web.config是: <connectionStrings> <add name="cnInvestTracker" connectionString="
我使用的是VS 2013和SQL Server 2014 以下是我的连接字符串:
using (SqlConnection sqlConnection = new SqlConnection("cnInvestTracker"))
{
}
我的web.config是:
<connectionStrings>
<add name="cnInvestTracker"
connectionString="Data Source=localhost;Initial Catalog=InvestTracker;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
当代码执行using行时,我收到一条错误消息。错误消息是:
初始化字符串的格式不符合规范
从索引0开始
导致错误的原因是什么?值“cnInvestTracker”本身不是有效的连接字符串。这就是您在此处尝试使用的内容:
new SqlConnection("cnInvestTracker")
该构造函数不需要连接字符串的名称,它需要:
(您可能需要添加对System.Configuration
的引用,并且您可能需要添加一些错误检查,以确保在尝试引用该名称之前存在该名称的连接字符串。)
一旦建立了连接,您可能需要对代码进行更多操作,因此下面是一个示例,说明了如果您希望使用.Fill()
你无法访问网络配置,我将为你发布一个修复程序。谢谢你,大卫。将在7分钟内接受回答
new SqlConnection(ConfigurationManager.ConnectionStrings["cnInvestTracker"].ConnectionString)
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["cnInvestTracker"].ConnectionString))
{
}
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);
}
}