如果c#Winforms中不存在数据库,如何创建数据库

如果c#Winforms中不存在数据库,如何创建数据库,c#,sql-server,winforms,C#,Sql Server,Winforms,如果数据库不存在,我想创建一个数据库。我正试图用这段代码做这件事,但它有错误,我得到这个消息 请帮忙 代码: 基于这篇具有类似数据库创建脚本的支持文章,我建议删除“CONTAINMENT=NONE”部分 默认情况下,所有SQL Server 2012及更高版本的数据库都将包含设置为“无”(),因此脚本可能不需要包含 可能ado.net不支持该tsql命令,还有一个完整的SQL Server管理对象库可用于处理高级数据库和模式脚本。我用它在应用程序启动期间创建了缺少的数据库,其中包含表定义等。基

如果数据库不存在,我想创建一个数据库。我正试图用这段代码做这件事,但它有错误,我得到这个消息

请帮忙

代码:


基于这篇具有类似数据库创建脚本的支持文章,我建议删除“CONTAINMENT=NONE”部分

默认情况下,所有SQL Server 2012及更高版本的数据库都将包含设置为“无”(),因此脚本可能不需要包含


可能ado.net不支持该tsql命令,还有一个完整的SQL Server管理对象库可用于处理高级数据库和模式脚本。我用它在应用程序启动期间创建了缺少的数据库,其中包含表定义等。

基于这篇支持文章,它有一个类似的数据库创建脚本,我建议删除“CONTAINMENT=NONE”部分

默认情况下,所有SQL Server 2012及更高版本的数据库都将包含设置为“无”(),因此脚本可能不需要包含


可能ado.net不支持该tsql命令,还有一个完整的SQL Server管理对象库可用于处理高级数据库和模式脚本。在应用程序启动期间,我使用它创建了缺少的数据库以及表定义等。

我的创建数据库功能

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;
    }
}
My 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;
}

我的创建数据库功能

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;
    }
}
My 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;
}

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

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();
        }
    }
}

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

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();
        }
    }
}

您正在使用哪个版本的Sql Server Express?它看起来像是Sql异常。如果我是你,我会在你使用的Sql Server Express的哪个版本中调试你的查询?它看起来像是Sql异常。如果我是你,我会用