在WPF应用程序中连接到只读嵌入式SQL Server压缩版(.sdf文件)

时间:2013-06-26 19:28:02

标签: sql-server-ce database-connection wpfdatagrid

我正在寻找以下解决方案:

查找格式正确的连接字符串到SQL Server压缩版文件(.sdf),该文件用作嵌入式资源,包含WPF应用程序中的引用(即只读)数据。

注意:请注意设置为“嵌入式资源”和“不要复制的操作词[构建操作] >“到输出目录设置。这意味着该文件不会作为独立实体物理复制到目标计算机,而是嵌入在应用程序可执行文件中。

到目前为止,我已经测试了一个解决方案,该解决方案允许使用简单的代码片段从嵌入式资源中获取.sdf文件(清单1):

清单1。

    Assembly _execAssembly = Assembly.GetExecutingAssembly();

    // helper snippet to find out all available embedded resource names
    string[] _resources = _execAssembly.GetManifestResourceNames();

    //.sdf included in IO.Stream

    System.IO.Stream _stream 
= Assembly.GetExecutingAssembly().GetManifestResourceStream("MyAssemblyName.App_Data.MyDB.sdf");

...需要其余代码将_ stream对象转换为.sdf并使用DataSet/TableAdapterSystem.Data.SqlServerCe对象连接到此文件; SqlCeConnectionSqlCeCommandSqlCeDataReader,如以下示例代码段所示(清单2):

清单2。

#region private: Get DataTable using SqlCeDataReader
/// <summary>
/// Get DataTable using SqlCeDataReader
/// </summary>
/// <param name="strConn">string</param>
/// <param name="strSQL">string</param>
/// <returns>DataTable</returns>
private static DataTable GetDataTableFromFileCeReader(string strConn, string strSQL)
{
    try
    {
        using (SqlCeConnection _connSqlCe = new SqlCeConnection(strConn))
        {
            using (SqlCeCommand _commandSqlCe = new SqlCeCommand())
            {
                _commandSqlCe.CommandType = CommandType.Text;
                _commandSqlCe.Connection = _connSqlCe;
                _commandSqlCe.CommandText = strSQL;
                _connSqlCe.Open();

                using (SqlCeDataReader _drSqlCe = _commandSqlCe.ExecuteReader()) {
                    DataTable _dt = new DataTable();
                    _dt.Load(_drSqlCe);
                    _connSqlCe.Close();
                    return _dt;
                }
            }
        }
    }
    catch { throw; }
}
#endregion

谢谢和问候。

1 个答案:

答案 0 :(得分:1)

这是我在SQL Server Compact Toolbox中使用的代码:

private static string CreateStore()
    {
        var factory = System.Data.Common.DbProviderFactories.GetFactory(Resources.SqlCompact35InvariantName);
        string fileName = GetSdfName();
        string connString = string.Format("Data Source={0};", fileName);
        bool created = false;
        if (!File.Exists(fileName))
        {
            using (Stream stream = new MemoryStream(Resources.SqlCe35AddinStore))
            {
                // Create a FileStream object to write a stream to a file 
                using (FileStream fileStream = File.Create(fileName, (int)stream.Length))
                {
                    // Fill the bytes[] array with the stream data 
                    byte[] bytesInStream = new byte[stream.Length];
                    stream.Read(bytesInStream, 0, (int)bytesInStream.Length);
                    // Use FileStream object to write to the specified file 
                    fileStream.Write(bytesInStream, 0, bytesInStream.Length);
                    created = true;
                }
            }
        }

        using (var conn = factory.CreateConnection())
        {
            if (created)
            {
                conn.ConnectionString = connString;
                conn.Open();
                using (var cmd = factory.CreateCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = "CREATE TABLE Databases (Id INT IDENTITY, Source nvarchar(2048) NOT NULL, FileName nvarchar(512) NOT NULL, CeVersion int NOT NULL)";
                    cmd.ExecuteNonQuery();
                }
            }
        }
        return connString;
    }

    private static string GetSdfName()
    {
        string fileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SqlCe35AddinStore.sdf");
        return fileName;
    }