简体   繁体   English

如何连接SDF数据库? 我试过没有连接字符串似乎工作

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

I've tried literally 50+ different attempts at my connection string for my local database and nothing seems to work. 我已尝试在我的本地数据库的连接字符串上进行50多次不同的尝试,似乎没有任何工作。 I'm essentially just trying to open a connection the database file so I can dump in the data I've pulled out of my excel spreadsheet. 我本质上只是试图打开数据库文件的连接,所以我可以转储我从excel电子表格中提取的数据。 I'm using Visual C# making an offline winform application. 我正在使用Visual C#制作离线winform应用程序。

No matter what connection string I try in my app.config, it always fails when it tries to write "dReader" to the database. 无论我在app.config中尝试什么连接字符串,它总是在尝试将“dReader”写入数据库时​​失败。

The error is usually this depending on what string I try: 错误通常取决于我尝试的字符串:

"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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)" “建立与SQL Server的连接时发生与网络相关或特定于实例的错误。未找到服务器或无法访问服务器。验证实例名称是否正确以及SQL Server是否配置为允许远程连接。(提供程序:命名管道提供程序,错误:40 - 无法打开与SQL Server的连接)“

I've gone through many online examples and resources and none seem to work. 我已经浏览了许多在线示例和资源,似乎没有任何工作。 I'm hoping someone here can point out why it's failing. 我希望这里有人可以指出它为什么会失败。

Here is my app.config in its latest form: 这是我最新形式的app.config:

<connectionStrings>
    <add name="DDP_Project.Properties.Settings.DDP_DatabaseConnectionString"
        connectionString="Data Source=E:\Other DDP Projects\DDP_Project_SDF\DDP_Project\DDP_Database.sdf;"
        providerName="Microsoft.SqlServerCe.Client.3.5" />
</connectionStrings>

Here is my form code: 这是我的表单代码:

    private void Profiles_Click(object sender, EventArgs e)
    {
        profilesDialog.FileName = "[YOUR_UPLOAD_FILE_HERE]";
        var result = profilesDialog.ShowDialog();

        if (result == DialogResult.OK)
        {
            HandleFileSelection();
        }
    }

    private void HandleFileSelection()
    {
        var file = profilesDialog.FileName;


         // Create a connection to the file datafile.sdf in the program folder
    string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\DDP_Database.sdf";
    SqlCeConnection connection = new SqlCeConnection("datasource=" + dbfile);


    string strConnection = ConfigurationManager.ConnectionStrings["DDP_Project.Properties.Settings.DDP_DatabaseConnectionString"].ConnectionString;


        //Create connection string to Excel work book
        string excelConnectionString = string.Format(
            @"Provider=Microsoft.Jet.OLEDB.4.0;
            Data Source=""{0}"";
            Extended Properties=""Excel 8.0;HDR=YES;""", file
        );

        //Create Connection to Excel work book
        OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
        OleDbCommand cmd = new OleDbCommand("SELECT [ID],[STATUS],[FAN_NUM],[PROFILE_NAME],[DESTINATION_HOST],[USER_ID],[USER_PASSWORD],[PROTOCOL],[PORT],[PATH],[CONTACT_NAME],[CONTACT_EMAIL],[CONTACT_PHONE],[CONTACT_ALT_PHONE],[CONTACT_CITY],[CONTACT_STATE],[CONTACT_CONTACT_TIME] FROM [Sheet1$]", excelConnection);

        excelConnection.Open();
        OleDbDataReader dReader;
        dReader = cmd.ExecuteReader();

        SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);

        sqlBulk.DestinationTableName = "Profiles";
        sqlBulk.ColumnMappings.Add("ID", "ID");
        sqlBulk.ColumnMappings.Add("STATUS", "STATUS");
        sqlBulk.ColumnMappings.Add("FAN_NUM", "FAN_NUM");
        sqlBulk.ColumnMappings.Add("PROFILE_NAME", "PROFILE_NAME");
        sqlBulk.ColumnMappings.Add("DESTINATION_HOST", "DESTINATION_HOST");
        sqlBulk.ColumnMappings.Add("USER_ID", "USER_ID");
        sqlBulk.ColumnMappings.Add("USER_PASSWORD", "USER_PASSWORD");
        sqlBulk.ColumnMappings.Add("PROTOCOL", "PROTOCOL");
        sqlBulk.ColumnMappings.Add("PORT", "PORT");
        sqlBulk.ColumnMappings.Add("PATH", "PATH");
        sqlBulk.ColumnMappings.Add("CONTACT_NAME", "CONTACT_NAME");
        sqlBulk.ColumnMappings.Add("CONTACT_EMAIL", "CONTACT_EMAIL");
        sqlBulk.ColumnMappings.Add("CONTACT_PHONE", "CONTACT_PHONE");
        sqlBulk.ColumnMappings.Add("CONTACT_ALT_PHONE", "CONTACT_ALT_PHONE");
        sqlBulk.ColumnMappings.Add("CONTACT_CITY", "CONTACT_CITY");
        sqlBulk.ColumnMappings.Add("CONTACT_STATE", "CONTACT_STATE");
        sqlBulk.ColumnMappings.Add("CONTACT_CONTACT_TIME", "CONTACT_CONTACT_TIME");

        sqlBulk.WriteToServer(dReader);
        sqlBulk.Close();
        excelConnection.Close();

    }

    private void profilesDialog_FileOk(object sender, EventArgs e)
    {


    }
}

} }

I think the problem you are seeing is that you are trying to use a SqlConnection to connect to a SQL Compact database. 我认为您遇到的问题是您正在尝试使用SqlConnection连接到SQL Compact数据库。 The .sdf is a compact database and you have to use the SqlCeConnection to connect to it. .sdf是一个紧凑的数据库,您必须使用SqlCeConnection连接它。 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. 而是将连接字符串传递给SqlBulkCopy对象,该对象从该字符串隐式创建SqlConnection。 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. 如果您注意到SqlBulkCopy的名称空间是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. 您看到错误的原因是它尝试通过SQL Server建立连接并且无法将连接字符串解析为SQL Server数据库。 Unfortunately, I don't think the System.Data.SqlServerCe has the equivalent to the SqlBulkCopy. 不幸的是,我不认为System.Data.SqlServerCe具有与SqlBulkCopy等效的功能。 Stick to using classes in System.Data.SqlServerCe and things should work as expected. 坚持使用System.Data.SqlServerCe中的类,事情应该按预期工作。 You just will have to do the processing in a more manual fashion. 您只需要以更手动的方式进行处理。

Try this... 尝试这个...

First: 第一:

Create first a test method which you may check if you can connect to sqlcedatabase. 首先创建一个测试方法,您可以检查是否可以连接到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.. 只需将excel文件数据加载到Datatable中,然后使用foreach将其保存在sql ce数据库文件中。

//Something like
//oledbcon
//oledb dataadapter
//datatable
// dapt.Fill(dt);

foreach(DataRow excel in dt.Rows)
{
    ceCmd.Parameters.AddWithValue("ID",excel["ID"]);
    ceCmd.ExecuteNonQuery();
}

Regards 问候

根据这篇文章,SqlCe不支持SqlBulkCopy。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM