【问题标题】:How to create database if not exist in c# Winforms如果在c#Winforms中不存在,如何创建数据库
【发布时间】:2017-01-22 19:30:39
【问题描述】:

如果数据库不存在,我想创建它。我正在尝试使用此代码执行此操作,但它有错误并且我收到此消息

enter image description here

请帮忙。

代码:

if(dbex == false)
{
    string str;

    SqlConnection mycon = new SqlConnection("Server=.\\sqlexpress;initial catalog=Masalehforoshi;Integrated security=SSPI;database=master");
    str = "CREATE DATABASE [Masalehforoshi] CONTAINMENT = NONE ON PRIMARY" +
                "(NAME=N'Masalehforoshi'," +
                @"FILENAME=N'C:\data\Masalehforoshi.mdf' " +
                ",SIZE=3072KB,MAXSIZE=UNLIMITED,FILEGROWTH=1024KB)" +
                "LOG ON (NAME=N'Masalehforoshi_log.', " +
                @"FILENAME=N'C:\Masalehforoshi_log.ldf' "+
                ",SIZE=1024KB,MAXSIZE=2048GB,FILEGROWTH=10%)";

    SqlCommand mycommand = new SqlCommand(str, mycon);

    try
    {
        mycommand.Connection.Open();
        mycommand.ExecuteNonQuery();
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.ToString(), "myprogram", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
    finally
    {
        if(mycon.State == ConnectionState.Open)
        {
            mycon.Close();
        }
    }
}

【问题讨论】:

  • 您使用的是什么版本的 Sql Server Express?
  • 貌似是sql异常。如果我是你,我会在 SQL Server Management Studio 中调试你的查询

标签: c# sql-server winforms


【解决方案1】:

我的创建数据库功能

public bool CreateDatabase(SqlConnection connection, string txtDatabase)
{
    String CreateDatabase;
    string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
    GrantAccess(appPath); //Need to assign the permission for current application to allow create database on server (if you are in domain).
    bool IsExits = CheckDatabaseExists(connection, txtDatabase); //Check database exists in sql server.
    if (!IsExits)
    {
        CreateDatabase = "CREATE DATABASE " + txtDatabase + " ; ";
        SqlCommand command = new SqlCommand(CreateDatabase, connection);
        try
        {
            connection.Open();
            command.ExecuteNonQuery();
        }
        catch (System.Exception ex)
        {
            MessageBox.Show("Please Check Server and Database name.Server and Database name are incorrect .", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            return false;
        }
        finally
        {
            if (connection.State == ConnectionState.Open)
            {
                connection.Close();
            }
        }
        return true;
    }
}

我的 GrantAccess 函数允许当前应用程序的权限

public static bool GrantAccess(string fullPath)
{
    DirectoryInfo info = new DirectoryInfo(fullPath);
    WindowsIdentity self = System.Security.Principal.WindowsIdentity.GetCurrent();
    DirectorySecurity ds = info.GetAccessControl();
    ds.AddAccessRule(new FileSystemAccessRule(self.Name,
    FileSystemRights.FullControl,
    InheritanceFlags.ObjectInherit |
    InheritanceFlags.ContainerInherit,
    PropagationFlags.None,
    AccessControlType.Allow));
    info.SetAccessControl(ds);
    return true;
}

检查数据库是否存在以下功能

public static bool CheckDatabaseExists(SqlConnection tmpConn, string databaseName)
{
    string sqlCreateDBQuery;
    bool result = false;

    try
    {
        sqlCreateDBQuery = string.Format("SELECT database_id FROM sys.databases WHERE Name = '{0}'", databaseName);
        using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn))
        {
            tmpConn.Open();
            object resultObj = sqlCmd.ExecuteScalar();
            int databaseID = 0;
            if (resultObj != null)
            {
                int.TryParse(resultObj.ToString(), out databaseID);
            }
            tmpConn.Close();
            result = (databaseID > 0);
        }
    }
    catch (Exception)
    {
        result = false;
    }
    return result;
}

【讨论】:

    【解决方案2】:

    根据这篇支持文章https://support.microsoft.com/en-us/kb/307283,它有一个类似的数据库创建脚本,我建议删除“CONTAINMENT = NONE”部分。

    默认情况下,所有 SQL Server 2012 及更高版本的数据库都将包含设置为 NONE。(https://msdn.microsoft.com/en-us/library/ff929071.aspx),因此您的脚本可能不需要它

    ado .net 可能不支持该 tsql 命令,还有一个完整的其他 SQL Server 管理对象库可用于处理高级数据库和架构脚本https://msdn.microsoft.com/en-us/library/ms162169.aspx。在应用程序启动期间,我用它来创建缺少表定义等的数据库。

    【讨论】:

      【解决方案3】:

      为了简化事情,这里有一个更短的解决方案。

      public void CreateDatabaseIfNotExists(string connectionString, string dbName)
      {
          SqlCommand cmd = null;
          using (var connection = new SqlConnection(connectionString))
          {
              connection.Open();
      
              using (cmd = new SqlCommand($"If(db_id(N'{dbName}') IS NULL) CREATE DATABASE [{dbName}]", connection))
              {
                  cmd.ExecuteNonQuery();
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2013-07-16
        • 1970-01-01
        • 2017-03-13
        • 1970-01-01
        • 1970-01-01
        • 2019-03-06
        • 1970-01-01
        • 2012-05-29
        • 1970-01-01
        相关资源
        最近更新 更多