0

I have created C# code which creates a .mdf SQL Server database file and this code works just fine.

There only few options are missing.

Especially I need to choose

  1. either database "Recovery model" is full mode or simple mode and
  2. either "Auto shrink" value is true or false during during creation of a database!

Code:

private void buttonCreateData_Click(object sender, EventArgs e)
{
    String CreateDatabase;
    SqlConnection connection = new SqlConnection("Server=(localdb)\\Projects;Integrated security=SSPI;database=master");
    CreateDatabase = "CREATE DATABASE " + textBoxDataName.Text + " " +
                     "ON PRIMARY " +
                     "(NAME = '" + textBoxDataName.Text + "', " +
                     "FILENAME = '" + Directory.GetCurrentDirectory() + "\\" + textBoxDataName.Text + ".mdf', " +
                     "SIZE = 6MB, MAXSIZE = 4GB, FILEGROWTH = 10%) " +
                     "LOG ON " + 
                     "(NAME = '" + textBoxDataName.Text + "_LOG" + "', " +
                     "FILENAME = '" + Directory.GetCurrentDirectory() + "\\" + textBoxDataName.Text + ".ldf', " +
                     "SIZE = 1MB, MAXSIZE = 200MB, FILEGROWTH = 10%)" +
                     "";

    SqlCommand command = new SqlCommand(CreateDatabase, connection);

    try
    {
        connection.Open();
        command.ExecuteNonQuery();
        MessageBox.Show("Database is created successfully", "Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (System.Exception ex)
    {
        MessageBox.Show(ex.ToString(), "Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    finally
    {
        if (connection.State == ConnectionState.Open)
        {
            connection.Close();
        }
    }
}

Remember I don't need to create the database firstly and then modify those two options. I need to set those two options during creation of database.

So what should I add in that code, I mean what kind of statement is missing in order to choose those two options during real-time?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1) [SET RECOVERY FULL](https://msdn.microsoft.com/en-us/library/ms186289.aspx), 2) google for auto-shrink, but it's [not safe](http://serverfault.com/q/20909). – Sinatr Feb 10 '15 at 16:06
  • Just wondering what the problem was for not wanting to create the database, and then modify the properties? Although CREATE DATABASE can't be part of a transaction, you still could create your own exception handling, where if any part failed you could drop the database. – David P Feb 10 '15 at 16:25

0 Answers0