代码之家  ›  专栏  ›  技术社区  ›  RKh

方法创建新的SQL Server CE DB文件。提出改进建议

  •  1
  • RKh  · 技术社区  · 15 年前

    我正在使用以下代码以编程方式创建sql server ce数据库文件。我用的是C 2008。

        /* Create a new SQL Server CE database file programatically */
        protected void CreateDB(string _databaseFileName, bool _encryptFile, string _password)
        {
            if (File.Exists(_databaseFileName))
                MessageBox.Show("A file with this name already exists.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            else
            {
                string connectionString = string.Format("DataSource=\"{0}\"; Password='{1}'", _databaseFileName, _password);
                SqlCeEngine engine = new SqlCeEngine(connectionString);
                engine.CreateDatabase();
            }
        }
    

    我想改进上面的代码。我的问题如下:

    1. 此方法包含在受保护的类中。我希望直接调用这些方法,而不创建此类的实例。建议一个没有开销的方法。

    2. 尽管我路过一个 布尔 以确定用户是否要加密文件,但不在连接字符串行中使用。我没有关注加密需要包含哪些其他参数以及如何包含加密算法。

    3. 我想用最少的开销包括异常处理。我想包括“ 使用 ,但不遵循如何使用此修改上述代码。

    1 回复  |  直到 15 年前
        1
  •  3
  •   Bryan    15 年前
    1. 制作方法 static .
    2. 如果在连接字符串中包含密码,则数据库文件将自动加密。
    3. 不知道你说的这个是什么意思。你应该抓住 SqlCeException 在其他地方。另外,你应该把 SqlCeEngine 在using语句中。

      try
      {
         string connectionString = string.Format("DataSource=\"{0}\"; Password='{1}'", _databaseFileName, _password);
         using (SqlCeEngine engine = new SqlCeEngine(connectionString))
         {
            engine.CreateDatabase();
         }
      }
      catch (SqlCeException)
      {
      }