问题
I searched SO but have not found a solution to my error.
I am using VS 2013, and SQL Server 2014.
Below is my connectionstring:
using (SqlConnection sqlConnection = new SqlConnection("cnInvestTracker"))
{
}
My web.config is:
<connectionStrings>
<add name="cnInvestTracker"
connectionString="Data Source=localhost;Initial Catalog=InvestTracker;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
I am getting an error message when the code executes the using line. The error message is:
Format of the initialization string does not conform to specification starting at index 0.
What is causing the error?
回答1:
The value "cnInvestTracker"
itself isn't a valid connection string. Which is what you're trying to use here:
new SqlConnection("cnInvestTracker")
That constructor doesn't want the name of a connection string, it wants the connection string itself:
new SqlConnection(ConfigurationManager.ConnectionStrings["cnInvestTracker"].ConnectionString)
(You may have to add a reference to System.Configuration
, and you may want to add some error checking to make sure a connection string of that name exists before trying to reference it.)
回答2:
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["cnInvestTracker"].ConnectionString))
{
}
you will probably want to do more with the code once you establish a connection so below is an example of what you can do if you are wanting to return data for example into a DataTable using the .Fill()
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);
}
}
来源:https://stackoverflow.com/questions/28787143/error-message-format-of-the-initialization-string-does-not-conform-to-specifica