如何在ASP.NET中连接到SQL Server Compact 4.0?

时间:2011-02-02 12:18:56

标签: sql asp.net connection sql-server-ce

我希望在我的ASP.NET应用程序中连接到SQL Server Compact 4.0。

以下是代码示例:

protected void Page_Load(object sender, EventArgs e)
{
    string connStr = "Data Source=D:\\MyDB.sdf;";
    string sqlStr = "select * from tblMyTable";

    var sqlDataSrc = new SqlDataSource(connStr, sqlStr);

    GridWithUrls.DataSource = sqlDataSrc;
    GridWithUrls.DataBind();
}

但我有下一个错误: “建立与SQL Server的连接时发生与网络相关或特定于实例的错误。找不到服务器或无法访问服务器。验证实例名称是否正确以及SQL Server是否配置为允许远程连接。(提供程序: SQL网络接口,错误:26 - 找到指定的服务器/实例时出错“”

SqlDataSource有三个参数的构造函数,其中一个是'providerName'所以,如何指定我想要使用Sql Server Compact提供程序? 我还添加了System.Data.SqlServerCe引用..

4 个答案:

答案 0 :(得分:22)

尝试:

providerName = "System.Data.SqlServerCe.4.0"

答案 1 :(得分:2)

将单个数据库文件(例如MySite.sdf)放在App_Data文件夹中。

connectionStrings添加web.config条目以允许连接到数据库:

<强>的web.config

<configuration>
   <connectionStrings>
      <add name="db" 
           connectionString="Data Source=|DataDirectory|\MySite.sdf"
           providerName="System.Data.SqlServerCe.4.0" />
   </connectionStrings>
   ...
</configuration> 

然后您可以通过连接字符串name db 创建所需的连接:

public static DbConnection CreateConnection()
{
   //Get connection string named "db"
   String csName = "db";
   ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings[csName];
   if (cs == null)
      throw new ConfigurationErrorsException("Could not find connection string \"" + csName + "\"");

   //Get a factory based on the "ProviderName" in the connection string
   DbProviderFactory factory = DbProviderFactories.GetFactory(cs.ProviderName);
   if (factory == null)
      throw new Exception("Unable to locate factory for " + cs.ProviderName);

   //Have the factory create us a connection object
   DbConnection conn = factory.CreateConnection();

   //Open the connection with the connection string from web.config
   conn.ConnectionString = cs.ConnectionString;
   conn.Open();

   //Give the ready connection to the user
   return conn;
}
  

注意:任何代码都会发布到公共域中。无需归属。

答案 2 :(得分:0)

看一下这里的例子:

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

如果要明确指定位置,请尝试:

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

答案 3 :(得分:0)

您可以先将数据拉入数据表:

        using (SqlCeConnection c = new SqlCeConnection(
            Properties.Settings.Default.DataConnectionString))
        {
            c.Open();

            // Create new DataAdapter
            using (SqlCeDataAdapter a = new SqlCeDataAdapter(
                "SELECT * FROM tblMyTable", c))
            {

                // Use DataAdapter to fill DataTable
                DataTable t = new DataTable();
                a.Fill(t);

                // Render data onto the screen
                dataGridView1.DataSource = t;
            }
        }