我无法打开与本地数据库的连接

I can't open the connection to the 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();
}

这里是异常错误:

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)

您的连接字符串不正确。它需要看起来像这样:

"Persist Security Info=False;Integrated Security=true;Initial Catalog=YOUR_DATABASE_NAME;server=(local)"

有关连接字符串的详细信息,请参阅此处:https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring(v=vs.110).aspx

由于您正在访问 SQL 服务器压缩数据库 .sdf 文件,因此您需要使用 SqlCeConnection and SqlCeCommand 类 而不是 SqlConnectionSqlCommand 类,您可以将其用于传统的 SQL 服务器连接。

此外,您可以使用类似于 the ones mentioned on ConnectionStrings.com 使用

的示例尝试在连接字符串中使用 Persist Security Info=False; 设置
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();
         }
    }
}