lkj
lkj

Reputation: 1033

Unable to make SQL Connection

Having trouble with my SQL connection code -

SqlConnection con = new SqlConnection("Data Source=D:\\MyDocuments\\Desktop\\WorkHours\\WorkHours\\App_Data\\Database1.sdf;" + "Trusted_Connection=true;");
con.Open();

Im only Going through those 2 lines, just trying to get the connection going and im getting this error :

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

i am 100% certain my database URL is correct. Help will be appreciated

Upvotes: 0

Views: 1101

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 416059

You are using the wrong connection type/provider.

Your database file has a *.sdf extension, which means you are using Sql Server Compact Edition, and Compact Edition needs the System.Data.SqlCe namespace and SqlCeConnection object.

Once you fix that, you still have two issues with your code:

  1. Don't hard-code the path to your database file. Add the file to Visual Studio as a resource, and have code to copy that to the Application Data folder on application startup, such that the copy fails if the file is already there.
  2. Make sure to embed your connection in a try/finally block, and for preference accomplish that with a using block.

Upvotes: 4

Kris Krause
Kris Krause

Reputation: 7326

http://www.connectionstrings.com/ is a great site and I am guilty of forgetting the proper connection string syntax too.

http://www.connectionstrings.com/sql-server-2008

If you are using compact edition -

http://www.connectionstrings.com/sql-server-2005-ce

Data Source =MyData.sdf; Persist Security Info =False; 

or...

Data Source =" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\MyData.sdf; Persist Security Info =False; 

Upvotes: 1

Related Questions