簡體   English   中英

c# Winforms中不存在時如何創建數據庫

[英]How to create database if not exist in c# Winforms

如果數據庫不存在,我想創建一個數據庫。 我正在嘗試使用此代碼執行此操作,但出現錯誤並收到此消息

在此處輸入圖片說明

請幫忙。

代碼:

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

我的創建數據庫功能

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

基於這篇支持文章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 在應用程序啟動期間,我用它來創建缺少表定義等的數據庫。

為了簡化事情,這里有一個更短的解決方案。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM