Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create database if not exist in c# Winforms

I want to create a database if it does not exist. I am trying to do it with this code but it has errors and I get this message

enter image description here

Please help.

Code:

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();
        }
    }
}
like image 892
mjd166 Avatar asked Mar 12 '23 03:03

mjd166


1 Answers

My Create Database function

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

    return false;
}

My GrantAccess function to allow permission for current app

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

Check Database exists function below

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;
}
like image 63
Balagurunathan Marimuthu Avatar answered Mar 19 '23 18:03

Balagurunathan Marimuthu