Search code examples
c#database-connectionsql-server-ce

I can't open the connection to the local database


I get an exception error for my code. Please help me - what is the problem? (I'm new to this :/)

My database is local database.

SqlConnection myconnection;

private void insertBtn_Click(object sender, EventArgs e)
{
        myconnection = new SqlConnection();
        myconnection.ConnectionString = "Data Source=C:\\Users\\Saeed\\Documents\\Visual Studio 2012\\Projects\\dictionary1\\dictionary1\\Database1.sdf";
        myconnection.Open();
        //string query = "INSERT INTO dictionary (id,enWord,faWord) VALUES (4,'pen','خودكار')";
        //SqlCommand cmd = new SqlCommand(query, myconnection);
        //cmd.ExecuteNonQuery();
}

Here is the exception 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)


Solution

  • Since you are accessing a SQL Server Compact Database .sdf file, you will want to use the SqlCeConnection and SqlCeCommand classes as opposed to the SqlConnection and SqlCommand classes, which you would use for traditional SQL Server connections.

    Additionally, you can try using the Persist Security Info=False; setting within your connection string using an example similar to the ones mentioned on ConnectionStrings.com using

    private void insertBtn_Click(object sender, EventArgs e)
    {
        // Open your connection
        using(var myConnection = new SqlCeConnection(@"Data Source=C:\Users\Saeed\Documents\Visual Studio 2012\Projects\dictionary1\dictionary1\Database1.sdf;Persist Security Info=False;"))
        {
             // Build your query
             var query = "INSERT INTO dictionary (id,enWord,faWord) VALUES (4,'pen','خودكار')"
             // Build a command to execute
             using(var myCommand = new SqlCeCommand(query,myConnection))
             {
                   // Open your connection
                   myConnection.Open();
                   // Execute your query
                   myCommand.ExecuteNonQuery();
             }
        }
    }