Lavanya Mohan
Lavanya Mohan

Reputation: 1516

How to resolve database connection string problems in asp.net?

I am developing an asp.net mvc3 application using Visual Studio 2010.I need to access the database. I wrote the connection string as

SqlConnection conn = new SqlConnection("Data Source=./App_Data/Abcd.mdf;Integrated Security=True;User Instance=True");

But, when I run the code, I get an error: 40 - Could not open a connection to SQL Server.

From the SQL Server Configuration Manager, I enabled TCP/IP but I still get the same exception.

I also tried changing the connection string to

SqlConnection conn = new SqlConnection("System.Configuration.ConfigurationManager.ConnectionStrings.ConnectionString");

But I got an exception that said "Format of the initialization string does not conform to specification starting at index 0."

How do I overcome this problem?

Thank you in advance for your help.

Upvotes: 0

Views: 2612

Answers (3)

Lijin Durairaj
Lijin Durairaj

Reputation: 5222

In VS click on server explorer and add the connection when the connection has been setup right click on the established connection and select properties you will get the properties window open. In that window select the connection string, which you can use in the sqlconnection

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

This will depend on the type of database you are using: SQL Express or SQL Developer/Standard. If you use SQL Express you may take a look at the following article illustrating different connection strings. For example:

Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|Abcd.mdf;Integrated Security=True;User Instance=True

If you are using the full version of SQL Server, your database is no longer stored in the App_Data folder. It is managed by SQL Server. Checkout the following site for connection strings in this case depending on your scenario.

Example:

Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

Upvotes: 1

Meysam  Savameri
Meysam Savameri

Reputation: 556

SqlConnection conn = new SqlConnection("Data Source=.\sqlexpress;database=dbname;AttachDbFilename=|DataDirectory|\Abcd.mdf;Integrated Security=True;User Instance=True");
or
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("webconfigconnectionname").ConnectionString);

Upvotes: 0

Related Questions