Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception when trying to connect to .sdf database

I have database in file C:\Users\Pawel\Documents\DB.sdf. How can I connect to it?

Simple code below does not work and generates exception.

Code:

[WebMethod]
public String TestCon()
{
    SqlConnection sql = new System.Data.SqlClient.SqlConnection(
        @"Data Source=C:\Users\Pawel\Documents\DB.sdf");

    string str = "OK";

    try
    {
        sql.Open();
        sql.Close();
    }
    catch (Exception ex)
    {
        str = ex.Message;
    }

    return str;
}

Result:
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)

What am I missing? What I should do to open connection correctly?

EDIT:
System.NotSupportedException: SQL Server Compact is not intended for ASP.NET development.
Great :P

like image 786
Ichibann Avatar asked May 10 '11 18:05

Ichibann


2 Answers

Consider using System.Data.SqlServerCe.SqlCeConnection:

System.Data.SqlServerCe.SqlCeConnection con = 
   new System.Data.SqlServerCe.SqlCeConnection(@"Data Source=C:\Users\Pawel\Documents\DB.sdf");

(Add a reference to System.Data.SqlServerCe, if necessary)

Also, to use it with ASP.NET, add:

AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true);
like image 116
Dmitry Avatar answered Nov 04 '22 03:11

Dmitry


Apparently, you are using a SQL Compact Edition (sdf file). Have you tried using SqlCeConnection instead of SqlConnection ?

As a bonus: if you dont want to mess with connectionstrings anymore, please try this.

Do do so, you have to add a reference to System.Data.SqlServerCe assembly.

like image 41
Larry Avatar answered Nov 04 '22 03:11

Larry