-3

I am new to SQL and trying to create a Database using C#. Here is my Code...

private void CreateDBBtn_Click(object sender, EventArgs e)
{
  String connectionString = GetConnectionString();
  SqlConnection connection = new SqlConnection(connectionString);
  connection.Open();

  String SQLCommand = "CREATE DATABASE MyDatabase ON PRIMARY " +
           "(NAME = MyDatabase_Data, " +
           "FILENAME = 'D:\\MyDatabase.mdf'," +
           "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%)";

  SqlCommand cmd = new SqlCommand(SQLCommand, connection);
  try
  {
    cmd.ExecuteNonQuery();
  }
  catch (SqlException ae)
  {
    MessageBox.Show(ae.Message);
  }
}

private String GetConnectionString()
{
   SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
   builder.DataSource = @".\SQLSERVER";
   builder.AttachDBFilename = @"D:\MyDatabase.mdf";
   builder.IntegratedSecurity = true;
   builder.ConnectTimeout = 30;
   builder.UserInstance = true;
   return builder.ConnectionString;
}

but it gives me error that...

enter image description here

Where as D:\MyDataBase.mdf file has size 3.13 MB on my PC.

Pankaj
  • 2,618
  • 3
  • 25
  • 47
  • 2
    Why not use the Database server to `Create` the Database.. – MethodMan Jun 18 '13 at 17:56
  • 7
    So set `SIZE = 5MB` then. Also `MAXSIZE = 10MB`? Surely you can afford more space than that? – Martin Smith Jun 18 '13 at 17:58
  • The error says it has to be 5MB. You said it is 3.13MB. Did you try boosting the initial size? Also, did you try scripting a samlple of the database from the sql server gui and then use that in your code? I wouldn't do it the way you are doing anyhow but those are some things I would try. – Mike Cheel Jun 18 '13 at 17:59
  • Yes, @MartinSmith, SIZE = 5B worked for me but I feel the Problem was this file Name builder.AttachDBFilename = @"D:\MyDatabase.mdf"; and the One in Create DataBase "FILENAME = 'D:\\MyDatabase.mdf', should also be different. – Pankaj Jun 18 '13 at 18:17
  • [refer this site][1]http://stackoverflow.com/questions/14034351/creating-a-sql-connection-in-c-sharp – Techrefresh Jun 18 '13 at 18:31

1 Answers1

-1

I completely agree with DJ KRAZE. It would take about two seconds to create that using whatever server manager you have.

khinkle
  • 111
  • 8
  • This is a comment, not an answer. – HardCode Jun 18 '13 at 18:46
  • 1
    I have to have 50 reputation points to be able to comment. Otherwise I would have. – khinkle Jun 18 '13 at 18:48
  • 1
    I agree @khinkle that it will take hardly 2 seconds to create using DataBase server but then I will never learn how to do that using C# and My First Line was "I am new to SQL and trying to create a Database using C#". – Pankaj Jun 18 '13 at 18:48