简体   繁体   English

在C#中创建(按需)SQL Server 2008 Express数据库的最佳实践?

[英]Best practice to create (on demand) SQL Server 2008 Express databases in C#?

The purpose is to handle the user's data (you can call them project, document, file, or whatever) in a brand new SQL Server 2008 Express database. 目的是在全新的SQL Server 2008 Express数据库中处理用户的数据(您可以将其称为项目,文档,文件或其他内容)。 The data are expected to occupy much less space than the 4GB available with the express edition (which is also free to distribute). 预计数据占用的空间将远远少于快递版本的4GB空间(也可免费分发)。

Eg, each time the user selects File->New command, a new empty database will be created at the specified location. 例如,每次用户选择File-> New命令时,将在指定位置创建一个新的空数据库。 On the other hand, a similar command, File->Open must provide support to retrieve the list of the databases to select one for opening. 另一方面,类似的命令File-> Open必须提供支持以检索数据库列表以选择一个用于打开的数据库。

So, the following issues must be resolved: a) The application must be able to create the connection string and attach the database to SQL Server 2008 Express through code (C#) b) The application must be able to retrieve (again through code) a list with all the available databases, to give the user a chance to select one to open. 因此,必须解决以下问题:a)应用程序必须能够创建连接字符串并通过代码(C#)将数据库附加到SQL Server 2008 Express b)应用程序必须能够检索(再次通过代码)a列出所有可用的数据库,以便用户有机会选择一个打开。

I think it would be helpful to have a template database in resources and copy it in the location specified by the user. 我认为在资源中使用模板数据库并将其复制到用户指定的位置会很有帮助。

Do you think it is a working solution? 你认为这是一个有效的解决方案吗? Do you have any suggestions? 你有什么建议吗?

There's lots you can do with Sql Server Management Objects (SMO): 你可以使用Sql Server管理对象(SMO)做很多事情:

// Add a reference to Microsoft.SqlServer.Smo
// Add a reference to Microsoft.SqlServer.ConnectionInfo
// Add a reference to Microsoft.SqlServer.SqlEnum

using Microsoft.SqlServer.Management.Smo;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;

public class SqlServerController
{

    private Server m_server = null;

    public SqlServerController(string server)
    {
        m_server = new Server(server);
    }

    public void AttachDatabase(string database, StringCollection files,
        AttachOptions options)
    {
        m_server.AttachDatabase(database, files, options);
    }

    public void AddBackupDevice(string name)
    {
        BackupDevice device = new BackupDevice(m_server, name);
        m_server.BackupDevices.Add(device);
    }

    public string GetServerVersion(string serverName)
    {
        return m_server.PingSqlServerVersion(serverName).ToString();
    }

    public int CountActiveConnections(string database)
    {
        return m_server.GetActiveDBConnectionCount(database);
    }

    public void DeleteDatabase(string database)
    {
        m_server.KillDatabase(database);
    }

    public void DetachDatabase(string database, bool updateStatistics, 
        bool removeFullTextIndex)
    {
        m_server.DetachDatabase(database, updateStatistics, removeFullTextIndex);
    }

    public void CreateDatabase(string database)
    {
        Database db = new Database(m_server, database);
        db.Create();
    }

    public void CreateTable(string database, string table, 
        List<Column> columnList, List<Index> indexList)
    {
        Database db = m_server.Databases[database];
        Table newTable = new Table(db, table);

        foreach (Column column in columnList)
            newTable.Columns.Add(column);

        if (indexList != null)
        {
            foreach (Index index in indexList)
                newTable.Indexes.Add(index);
        }

        newTable.Create();

    }

    public Column CreateColumn(string name, DataType type, string @default,
        bool isIdentity, bool nullable)
    {
        Column column = new Column();

        column.DataType = type;
        column.Default = @default;
        column.Identity = isIdentity;
        column.Nullable = nullable;

        return column;
    }

    public Index CreateIndex(string name, bool isClustered, IndexKeyType type,
      string[] columnNameList)
    {

        Index index = new Index();

        index.Name = name;
        index.IndexKeyType = type;
        index.IsClustered = isClustered;

        foreach (string columnName in columnNameList)
            index.IndexedColumns.Add(new IndexedColumn(index, columnName));

        return index;
    }

}

An alternate solution is to use SQLite rather than SQL Express. 另一种解决方案是使用SQLite而不是SQL Express。 You can even continue to use ADO.NET if you use this solution . 如果使用此解决方案,您甚至可以继续使用ADO.NET。 SQLite databases are simply files, and your connection strings can refer to the file path. SQLite数据库只是文件,您的连接字符串可以引用文件路径。 When a user wants to open their file, they can select an actual file. 当用户想要打开他们的文件时,他们可以选择一个实际的文件。

I get the impression that this database will live locally on user's machine. 我得到的印象是这个数据库将在用户的机器上本地生存。 If that's the case, sql server express is not usually a good database choice. 如果是这种情况,sql server express通常不是一个很好的数据库选择。 It's a server-class engine rather than a desktop or in process engine. 它是服务器级引擎,而不是桌面或流程引擎。 Instead, there are a number of good in process engines you can use: Sql Server Compact Edition, Sqlite (as mentioned by Jacob) or even Access. 相反,您可以使用许多优秀的流程引擎:Sql Server Compact Edition,Sqlite(如Jacob所述)甚至是Access。

如果您认为SQL Server Express 2008是正确的选择(尽管sqllite看起来确实更合适),我会考虑使用用户实例 ,这将允许非管理员在您描述的文件中添加数据库。

This article shows how to create a new database, and attach it to a SQL Server database instance: 本文介绍如何创建新数据库,并将其附加到SQL Server数据库实例:

How to: Attach a Database File to SQL Server Express 如何:将数据库文件附加到SQL Server Express
http://msdn.microsoft.com/en-us/library/ms165673.aspx http://msdn.microsoft.com/en-us/library/ms165673.aspx

These article shows how to manage the attaching and detaching of existing databases: http://msdn.microsoft.com/en-us/library/ms190794.aspx 这些文章介绍了如何管理现有数据库的附加和分离: http//msdn.microsoft.com/en-us/library/ms190794.aspx

http://www.databasejournal.com/features/mssql/article.php/2224361/Attaching-and-Detaching-Databases-on-SQL-Server.htm http://www.databasejournal.com/features/mssql/article.php/2224361/Attaching-and-Detaching-Databases-on-SQL-Server.htm

For the following connection string for SQL Server 2008 R2. 对于SQL Server 2008 R2的以下连接字符串。

   <connectionstring>Data Source=.\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True;Pooling=True</connectionstring>

you can do 你可以做

  var connectionString = new SqlConnectionStringBuilder(connectionString);

  var serverConnection = new ServerConnection("DatabaseInstanceName in server");

  var serverInstance = new Server(serverConnection);

  if (serverInstance.Databases.Contains(connectionString.InitialCatalog))
      serverInstance.KillDatabase(connectionString.InitialCatalog);

  var db = new Database(serverInstance, connectionString.InitialCatalog);

  try
  {
     db.Create();
  }
  catch (SqlException ex)
  {
     throw;
  }

Thanks to Mr. Harvey for pointing the right direction. 感谢哈维先生指出了正确的方向。 Although in my case, I have to make these small changes. 虽然在我的情况下,我必须做出这些小改动。 Because, I use the windows authentication. 因为,我使用的是windows身份验证。

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

相关问题 使用C#安装SQL Server 2008 R2 Express - Install SQL Server 2008 R2 Express using C# 使用Winforms(C#)与SQL Server 2008 Express连接 - Connect with SQL Server 2008 Express using Winforms (C#) 使用C#连接到SQL Server 2008 Express数据库 - Connect to SQL Server 2008 Express database using C# c# 2008 SQL Server Express 连接字符串 - c# 2008 SQL Server Express Connection String 使用C#和SQL Server解析逗号分隔的字符串的最佳实践 - Best practice to parse a comma separated string with C# and SQL Server C#Express Edition + SQL Server 2008 R2 Express; 正在运行时重新创建的数据库文件 - C# Express Edition + SQL Server 2008 R2 Express; Database file being recreated on run C#2010 Express + SQL Server 2008 Express-连接“登录失败” - C# 2010 Express + SQL Server 2008 Express - Connection “Login failed” 从C#查询SQL Server 2008 R2中的master.sys.databases视图不起作用 - Querying master.sys.databases view in SQL Server 2008 R2 from c# is not working C#,Sql Server 2008:将大型结果集流式传输给最终用户仅适用于某些数据库 - C#, Sql Server 2008: Stream large result set to end user only works on some databases 如何创建一个c#程序集加载到sql server 2008中 - Howto create a c# assembly to load into sql server 2008
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM