How can I connect to a SDF database? No connection string I try seems to work

前端 未结 3 1073

I\'ve tried literally 50+ different attempts at my connection string for my local database and nothing seems to work. I\'m essentially just trying to open a connection the d

相关标签:
3条回答
  • 2020-12-19 06:19

    According to this post, SqlBulkCopy isn't supported with SqlCe.

    0 讨论(0)
  • 2020-12-19 06:22

    Try this...

    First:

    Create first a test method which you may check if you can connect to sqlcedatabase.

    private void testconnection()
    {
      string strConnection = ConfigurationManager.ConnectionStrings["DDP_Project.Properties.Settings.DDP_DatabaseConnectionString"].ConnectionString;                     
      using (var conn = new SqlCeConnection(string.Format("Data Source={0};Max Database Size=4091;Max Buffer Size = 1024;Default Lock Escalation =100;", strConnection)))
      {
         conn.Open();
    
         try
         {
             //your Stuff                    
         }
         catch (SqlCeException)
         {
             throw;
         }
         finally
         {
             if (conn.State == ConnectionState.Open) conn.Close();
         }
      }
    }
    

    Second:

    Just Load your excel file Data into a Datatable and use foreach then save it on your sql ce database file..

    //Something like
    //oledbcon
    //oledb dataadapter
    //datatable
    // dapt.Fill(dt);
    
    foreach(DataRow excel in dt.Rows)
    {
        ceCmd.Parameters.AddWithValue("ID",excel["ID"]);
        ceCmd.ExecuteNonQuery();
    }
    

    Regards

    0 讨论(0)
  • 2020-12-19 06:28

    I think the problem you are seeing is that you are trying to use a SqlConnection to connect to a SQL Compact database. The .sdf is a compact database and you have to use the SqlCeConnection to connect to it. You create the connection using this but then you don't use it. Instead you pass in the connection string to the SqlBulkCopy object which implicitly creates a SqlConnection from that string. I'm assuming it is on that line where you are getting the error. If you notice the namespace of the SqlBulkCopy is System.Data.SqlClient. The reason you are seeing the error is that its trying to go through SQL Server to make the connection and cannot resolve your connection string to a SQL Server database. Unfortunately, I don't think the System.Data.SqlServerCe has the equivalent to the SqlBulkCopy. Stick to using classes in System.Data.SqlServerCe and things should work as expected. You just will have to do the processing in a more manual fashion.

    0 讨论(0)
提交回复
热议问题