如何使用C#连接到Winform应用程序中的.sdf文件?

时间:2013-06-04 11:30:07

标签: c# winforms sql-server-ce

我正在尝试将.sdf文件与winform连接。这就是我想要做的事情:

SqlConnection con = new SqlConnection();
        con.ConnectionString=@"Data Source=D:\TestWinform\MyDB.sdf;Persist Security Info=True";
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into User(Name) values('" + txt.Text + "')";
        cmd.Connection = con;


        con.Open();   // giving exception in this line
        cmd.ExecuteNonQuery();
        con.Close();

但是我遇到了一个问题,con.Open()给出了这个例外

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) 

我应该怎么做,我猜它找不到文件,但.sdf文件就在那个位置 所以请帮助我这个

1 个答案:

答案 0 :(得分:6)

您的连接对象有误。您正在使用Sql compact,因此您必须使用SqlCeConnectionSqlConnection用于连接SQL Server。

按照link对问题进行排序。

这是sample

相关问题